def run(): channel = grpc.insecure_channel('localhost:50051') stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='you')) print("Greeter client received: " + response.message) response = stub.SayHelloAgain(helloworld_pb2.HelloRequest(name='you')) print("Greeter client received: " + response.message)
def send_hello(self, name): is_error = False error_msg = '' try: # s 是一个基于 dict 的实例 s = helloworld_pb2.HelloRequest(name=name) # 调用 SayHello 向 Server 发送信息 # 这个函数是在 __init__ 时被定义的,定义时,添加了3个参数,分别定义了唯一标识、指定压缩格式(str to 二进制)、解压缩格式。 # 所以这里调用时,会被自动压缩成对应的参数,然后发送到 server 去。 # 如果只看转成二进制字符串这一步,相当于 # import grpc._common as common # common.serialize(s, helloworld_pb2.HelloRequest.SerializeToString) # 然后你也可以拿去,用自己的通信方式去发送数据 response = self.stub.SayHello(s) except BaseException as e: # 这个错误信息可能是服务器连接失败 is_error = True error_msg = e error_log(e.details()) return {'code': 0, 'msg': 'send error', 'data': e} finally: # 组织返回信息 if is_error: return {'code': 0, 'msg': error_msg, 'data': {}} else: return {'code': 200, 'msg': 'success', 'data': response}
def run(): # 连接 rpc 服务器 channel = grpc.insecure_channel('localhost:50001') # 调用 rpc 服务 stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='World')) print("Greeter client received: " + response.message)
def get_say_hello_often(self, name): message = helloworld_pb2.HelloRequest(name=name) response = self.stub.SayHelloOften(message) for r in response: print(r)
def get_say_hello(self, name): response = self.stub.SayHello(helloworld_pb2.HelloRequest(name=name)) print("Greeter client received: " + response.message)