learning grpc

helloworld.proto代码如下:

syntax = "proto3";
package helloworld;

service Greeter{
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

 解释:定义了一个Greeter的服务,会跟下面的server.py里面的class类名同名。sayhello是整个消息来回过程中client要调用的定义在server端的函数名。HelloRequest是client发送给server消息时用的函数。把需要传给server的值赋给name这个变量。server端靠HelloReply函数接收消息,消息在request里。通过request.name得到name的值。把该值赋给message后通过HelloReply函数传给client。client从HelloRequest函数的返回值里得到server发来的回应,该回应.mesage可以取出里面的值。

通过编译helloworld.proto生成了helloworld_pd2.py和helloworld_pd2_grpc.py,下面代码都会用到(import helloworld_pd2 和import helloworld_pd2_grpc)。

client.py代码如下:

#coding:utf-8
from __future__ import print_function
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
import time

def hello(name):
    # 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('127.0.0.1:50051') as channel:
        stub =helloworld_pb2_grpc.GreeterStub(channel)
        response = stub.SayHello(helloworld_pb2.HelloRequest(name=name))
        print(response.message)

if __name__ == '__main__':
    hello("1234")
 
 
server.py代码如下:
from concurrent import futures
import time
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24

class Greeter(helloworld_pb2_grpc.GreeterServicer):
    # 工作函数
    def SayHello(self, request, context):
        return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)


def serve():
    # gRPC 服务器
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:50051')
    server.start()  # start() 不会阻塞,如果运行时你的代码没有其它的事情可做,你可能需要循环等待。
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()

 

posted on 2019-05-07 16:16  大老虎🐯  阅读(124)  评论(0编辑  收藏  举报