• 技术文章 >Python技术 >Python基础教程

    python中Protobuf创建服务端代码

    小妮浅浅小妮浅浅2021-04-27 10:03:02原创1610

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    1、创建和运行 Greeter 服务可以分为两个部分:

    执行服务定义的生成的服务接口:完成实际服务“工作”的功能。

    在gRPC服务器上运行,监听来自客户端的请求并传送服务响应。

    2、在当前目录,打开文件 greeter_server.py,实现一个新的函数:

    from concurrent import futures
    import time
     
    import grpc
     
    import hello_pb2
    import hello_pb2_grpc
     
    _ONE_DAY_IN_SECONDS = 60 * 60 * 24
     
     
    class Greeter(hello_pb2_grpc.GreeterServicer):
    # 工作函数
        def SayHello(self, request, context):
            return hello_pb2.HelloReply(message='Hello, %s!' % request.name)
     
     
    def serve():
        # gRPC 服务器
        server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        hello_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()

    以上就是python中Protobuf创建服务端代码的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程

    专题推荐:python protobuf
    品易云
    上一篇:python Protobuf定义消息类型 下一篇:python中self的原理探究

    相关文章推荐

    • python plot()函数的基本介绍• python抽象类的知识整理• python模块的搜索路径如何理解?• python包的导入方式有几种• python中gRPC是什么?• python Protobuf定义消息类型

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网