python gRPC 简单示例

转载自:https://blog.csdn.net/ctwy291314/article/details/91866261 修改了部分代码

Ubuntu18.04安装gRPC

  • protobuf-compiler-grpc安装
    sudo apt-get install protobuf-compiler-grpc
  • protobuf-compiler安装
    sudo apt-get install protobuf-compiler
  • gRPC 的安装
    pip install grpcio
  • 安装 ProtoBuf 相关的 python 依赖库
    pip install protobuf
  • 安装 python grpc 的 protobuf 编译工具
    pip install grpcio-tools

编写示例工程

  • 工程结构
    在这里插入图片描述
  • 编写 proto 文件
    在工程下新建stream目录,新建stream.proto文件,文件可名称任意
    syntax = "proto3";
    package stream;
    service StreamService {
      rpc SimpleFun(RequestData) returns (ResponseData){}
    }
    message RequestData {
      string text = 1;
      int32 name = 2; #参数增加数字增加
    }
    
    message ResponseData {
      string text = 1;
    }
    
  • 编译 protobuf
    切换至stream目录,执行以下命令:
    python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./stream.proto

在 stream目录中执行编译,会生成:stream_pb2.py 与 stream_pb2_grpc.py,需修正stream_pb2_grpc.py的引用stream__pb2的路径

  • 实现 server 端,simple_server.py
    #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    import grpc
    import time
    from concurrent import futures
    from stream import stream_pb2, stream_pb2_grpc
    
    _ONE_DAY_IN_SECONDS = 60 * 60 * 24
    _HOST = 'localhost'
    _PORT = '8883'
    
    
    class servicer(stream_pb2_grpc.StreamServiceServicer):
    
        def SimpleFun(self, request, context):
            strcontent = request.text
            print("received: " + strcontent)
            print("received: " + str(request.name))
            print("Call SimpleFun End")
            return stream_pb2.ResponseData(text=('hello,gRPC'))
    
    
    def serve():
        grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
        stream_pb2_grpc.add_StreamServiceServicer_to_server(servicer(), grpcServer)
        grpcServer.add_insecure_port(_HOST + ':' + _PORT)
        grpcServer.start()
        try:
            while True:
                time.sleep(_ONE_DAY_IN_SECONDS)
        except KeyboardInterrupt:
            grpcServer.stop(0)
    
    
    if __name__ == '__main__':
        serve()
    
  • 实现 client端,simple_client.py
    #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    import grpc
    from stream import stream_pb2, stream_pb2_grpc
    
    _HOST = 'localhost'
    _PORT = '8883'
    
    def run():
        conn = grpc.insecure_channel(_HOST + ':' + _PORT)
        client = stream_pb2_grpc.StreamServiceStub(channel=conn)
        response = client.SimpleFun(stream_pb2.RequestData(text='hello,world!', name = 0))
        print("received: " + response.text)
    
    if __name__ == '__main__':
        run()
    
  • 执行结果
    先启动simple_server.py再启动simple_client.py
    在这里插入图片描述在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值