記錄下grpc的例子

1 安裝 pip install grpciopython

pip install protobuf服務器

pip install grpcio_toolscode

2 編寫proto3文件 stream_mao.protoorm

syntax = "proto3";server

package stream_mao;ip

service Stream_mao_Service {ci

rpc SimpleFun(RequestData) returns (ResponseData){}

}rpc

message RequestData {string

string text = 1; }pip

message ResponseData {

repeated int32 t=1;

}

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./stream_mao.proto

編寫服務器端:

import grpc

import time

from concurrent import futures

from test_1 import stream_mao_pb2, stream_mao_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

_HOST = '192.168.1.103'

_PORT = '8883'

class servicer(stream_mao_pb2_grpc.Stream_mao_ServiceServicer):

def SimpleFun(self, request, context):

    str = request.text
	
    a=[1,2]
	
    for i in range(5):
	
        b=[2,3,4,5]
		
        a=a+b
		
		
    a=a+[2]
	
    print("received:"+str)
	
    time.sleep(14)
	
    return stream_mao_pb2.ResponseData(t=a)

def serve():

grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
    stream_mao_pb2_grpc.add_Stream_mao_ServiceServicer_to_server(servicer(),grpcServer)
    grpcServer.add_insecure_port(_HOST+':'+_PORT)
    grpcServer.start()
    print("start server at port {} ...".format(_PORT))
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        grpcServer.stop(0)

if name=='main': serve()

編寫客戶端

import grpc

from test_1 import stream_mao_pb2,stream_mao_pb2_grpc

import time

#注意,爲啥要和服務端的地址同樣

_HOST = '192.168.1.103'

_PORT = '8883'

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

def run():

conn = grpc.insecure_channel(_HOST+':'+_PORT)

client = stream_mao_pb2_grpc.Stream_mao_ServiceStub(channel=conn)

response=client.SimpleFun(stream_mao_pb2.RequestData(text='hello'))

print(response.t)

try:
    while True:
	
        time.sleep(_ONE_DAY_IN_SECONDS)
		
except KeyboardInterrupt:

    client.stop(0)

if name=='main': run()

相關文章
相關標籤/搜索