1. 程式人生 > >python在Linux中實現GRPC簡單命令

python在Linux中實現GRPC簡單命令

  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, 觀察服務端出現提示及返回訊息即成功.