python在Linux中实现GRPC简单命令

版权声明:未经允许不得转载 https://blog.csdn.net/etfsoft/article/details/84281386
  1. 先确认安装python3后安装gRPC:
pip install grpcio
pip install protobuf
pip install grpcio-tools

2.编辑或使用服务方提供的 proto文件名.proto 文件
3.编译 proto文件名.proto 文件

python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. proto文件名.proto

4.编写Server.py代码

#coding:utf-8
from concurrent import futures
import time
import grpc
import proto文件名_pb2
import proto文件名_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24


class Greeter(proto文件名_pb2_grpc.GreeterServicer):
    # 工作函数
    def SayHello(self, request, context):
        print(request.name)
        print(request.info)
        message = "我是服务器,您的消息: " + request.name;
        return proto文件名_pb2.HelloReply(message = message)


def server():
    # gRPC 服务器
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    proto文件名_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:50051')
    print("服务已开启,等待消息...")
    server.start()  # start() 不阻塞,等待。
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    server()

5.编写cnt.py客户端文件

#coding:utf-8
from __future__ import print_function

import grpc

import proto文件名_pb2
import proto文件名_pb2_grpc


def run():
    channel = grpc.insecure_channel('localhost:50051')
    stub = proto文件名_pb2_grpc.GreeterStub(channel)
    response = stub.SayHello(proto文件名_pb2.HelloRequest(name='我是客户端,我想测试!',info='info'))
    print("Greeter client received: " + response.message)


if __name__ == '__main__':
    run()

6.运行 python3 server.py 进入等待
7.另启运行 python3 cnt.py, 观察服务端出现提示及返回消息即成功.

猜你喜欢

转载自blog.csdn.net/etfsoft/article/details/84281386