1 安装 pip install grpcio
pip install protobuf
pip install grpcio_tools
2 编写proto3文件 stream_mao.proto
syntax = "proto3";
package stream_mao;
service Stream_mao_Service {
rpc SimpleFun(RequestData) returns (ResponseData){}
}
message RequestData {
string text = 1; }
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()