grpc python stream_记录下grpc的例子

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值