def collect(stub): mylist = [] mylist.append(echo_pb2.EchoRequest(content="hello")) mylist.append(echo_pb2.EchoRequest(content="world")) mylist.append(echo_pb2.EchoRequest(content="!")) response = stub.Collect(iter(mylist)) print(response)
def expand(stub): responses = stub.Expand( echo_pb2.EchoRequest(content="hello world ! welcome !")) for res in responses: print(res) print("trailing metadata is:") print(responses.trailing_metadata())
def run(): with grpc.insecure_channel('localhost:9090') as channel: stub = echo_pb2_grpc.EchoServiceStub(channel) response = stub.Echo(echo_pb2.EchoRequest(message="huwwo")) print( f"received: { response.message }, count = { response.message_count }" )
def invoke_echo(stub, input_msg): messages = [] messages.append(echo_pb2.EchoRequest(msg=input_msg, log=True)) responses = stub.echo(iter(messages)) # responses = stub.EchoService(iter(messages)) for response in responses: print('### Reply from EchoService: {}'.format(response.resp))
def chat(stub): mylist = [] mylist.append(echo_pb2.EchoRequest(content="hello")) mylist.append(echo_pb2.EchoRequest(content="world")) mylist.append(echo_pb2.EchoRequest(content="!")) responses = stub.Chat(iter(mylist), metadata=( ('initial-metadata-1', 'The value should be str'), ('binary-metadata-bin', b'With -bin surffix, the value can be bytes'), ('accesstoken', 'gRPC Python is great'), )) for response in responses: print(response) print("trailing metadata is:") print(responses.trailing_metadata())
def w(filename): req = echo_pb2.EchoRequest(firstname='john', lastname='doe') msg = binascii.b2a_hex(req.SerializeToString()) frame = '00' + hex(len(msg) / 2).lstrip("0x").zfill(8) + msg print 'Raw Encode: ' + frame f = open(filename, "wb+") f.write(binascii.a2b_hex(frame)) f.close()
def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel('localhost:50051') as channel: stub = echo_pb2_grpc.EchoServiceStub(channel) response = stub.Echo(echo_pb2.EchoRequest(message='you')) print("Client received: " + response.message)
def run(host, port): _TIMEOUT_SECONDS = 1 cc = grpc.ssl_channel_credentials(open('CA_crt.pem', 'rb').read()) channel = grpc.secure_channel('{}:{}'.format(host, port), cc) #channel = grpc.insecure_channel(host,port) stub = echo_pb2_grpc.EchoServerStub(channel) response = stub.SayHello( echo_pb2.EchoRequest(firstname='john', lastname='doe'), _TIMEOUT_SECONDS) print(response)
def w(filename): req = echo_pb2.EchoRequest(firstname='john', lastname='doe') msg = binascii.b2a_hex(req.SerializeToString()) ## wireformat frame = '00' + hex( len(msg) // 2).lstrip("0x").zfill(8) + msg.decode("utf-8") ## raw #frame = msg.decode("utf-8") print('Raw Encode: ' + frame) f = open(filename, "wb+") f.write(binascii.a2b_hex(frame)) f.close()
def run(host, port): _TIMEOUT_SECONDS = 1 cc = ssl_credentials = grpc.ssl_channel_credentials( open('CA_crt.pem').read()) channel = implementations.secure_channel(host, port, cc) #channel = implementations.insecure_channel(host,port) stub = echo_pb2.beta_create_EchoServer_stub(channel) response = stub.SayHello( echo_pb2.EchoRequest(firstname='john', lastname='doe'), _TIMEOUT_SECONDS) print response
async def requests(idx, echo_stub): global finish_benchmark times = [] while not finish_benchmark: start = time.monotonic() echo_reply = await echo_stub.Hi(echo_pb2.EchoRequest(message="ping")) elapsed = time.monotonic() - start times.append(elapsed) return times
def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel('localhost:50051') as channel: stub = echo_pb2_grpc.EchoStub(channel) # response = stub.SayHello(echo_pb2.HelloRequest(name='you')) # print("Greeter client received: " + response.message) value = "payload (test message)" request = echo_pb2.EchoRequest(message=value) response = stub.Reply(request) print(f"Response from the server: '{response.message}'")
async def benchmark(loop, seconds=DEFAULT_SECONDS, concurrency=DEFAULT_CONCURRENCY): global finish_benchmark print("Creating stubs and warmming up ....") stubs = [] channels = [] for i in range(concurrency): channel = Channel('127.0.0.1', 50051, loop=loop) echo_stub = echo_grpc.EchoStub(channel) echo_reply = await echo_stub.Hi(echo_pb2.EchoRequest(message="ping")) assert echo_reply.message stubs.append(echo_stub) channels.append(channel) print("Starting tasks ....") tasks = [ asyncio.ensure_future(requests(idx, echo_stub)) for idx, echo_stub in enumerate(stubs) ] await asyncio.sleep(seconds) print("Finishing tasks ....") finish_benchmark = True while not all([task.done() for task in tasks]): await asyncio.sleep(0) for channel in channels: channel.close() times = [] for task in tasks: times += task.result() times.sort() total_requests = len(times) avg = sum(times) / total_requests p75 = times[int((75 * total_requests) / 100)] p90 = times[int((90 * total_requests) / 100)] p99 = times[int((99 * total_requests) / 100)] print('QPS: {0}'.format(int(total_requests / seconds))) print('Avg: {0:.6f}'.format(avg)) print('P75: {0:.6f}'.format(p75)) print('P90: {0:.6f}'.format(p90)) print('P99: {0:.6f}'.format(p99))
def main(): logger = logging.getLogger('') handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) channel = Channel() channel.connectTCP('', 8888) echo = echo_pb2.Echo_Stub(channel) proxy = Proxy(echo) request = echo_pb2.EchoRequest() request.info = 'Hello!!!' proxy.Echo.Hello(request, Print, ErrorCallback)
def main(): channel = implementations.insecure_channel('localhost', 50051) stub = echo_pb2.beta_create_Echo_stub(channel) message = echo_pb2.EchoRequest(message='foo') response = stub.DoEcho(message, 15)
# test server side import time from concurrent import futures import grpc import echo_pb2 as echo import echo_pb2_grpc as echo_grpc with grpc.insecure_channel('127.0.0.1:1443') as channel: stub = echo_grpc.EchoStub(channel) req = echo.EchoRequest() req.message = 'F**k U' rsp = stub.Echo(req) print(rsp)
def DoEcho(self, request, context): return echo_pb2.EchoRequest(message=request.message)
errmsg = "AttributeError " + method_name + " for class " + class_name + " in " + module_name + ".py:" + e.message print errmsg return (-6, errmsg) except Exception, e: errmsg = "Py exec function (%s.%s) failed: %s" % ( class_name, method_name, e.message) print errmsg print 'invoke method failed.' print '%s' % traceback.format_exc() return (-21, errmsg) if __name__ == "__main__": import echo_pb2 request = echo_pb2.EchoRequest() request.part1 = 'hello' request.part2 = 'from python' request.number = 15 req_data = request.SerializeToString() ext_info = [ 1, ] (ret, rsp_data) = process('echosample.EchoService.echoCall', req_data, ext_info) if ret == 0: response = echo_pb2.EchoResponse() response.ParseFromString(rsp_data) print response
def echo(stub): request = echo_pb2.EchoRequest(content="hello world!") response = stub.Echo(request) print(response)
size = int(packet_header[1]) while True: return_data += self._socket_connection.recv(size) if len(return_data) >= size: break raw_meta = return_data[0:packet_header[2]] rpc_meta = baidu_rpc_meta_pb2.RpcMeta() rpc_meta.ParseFromString(raw_meta) #print(rpc_meta) raw_res = return_data[packet_header[2]:] res_pb.ParseFromString(raw_res) return True except Exception as e: print("exception " + str(e)) return False if __name__ == '__main__': import echo_pb2 ip = "localhost" port = 8000 client = BrpcClient(ip, port) req_msg = echo_pb2.EchoRequest() req_msg.message = "hello world" res_msg = echo_pb2.EchoResponse() rc = client.send_req("EchoService", "Echo", req_msg, res_msg) if not rc: sys.exit(1) print("recieve the response sucessfully") print("response: {0}".format(res_msg.message))
async def send(stream: grpc.aio.StreamStreamCall): await stream.wait_for_connection() for n in range(0, 1_000_000): await asyncio.sleep(0.001) await stream.write(echo_pb2.EchoRequest(message=f"message: {n}"))