pip install grpcio
pip install protobuf
pip install grpcio-tools
data.proto:
syntax = 'proto3';
// 服务定义
service data{
// 函数定义 data_request参数 data_reply返回数据
rpc serving(data_request) returns (data_reply) {}
}
message data_request{
string cmd= 1;
}
message data_reply{
string values = 1;
}
python -m grpc_tools.protoc -I. --python_out=../ --grpc_python_out=../ ./data.proto
data_server.py:
import data_pb2
import data_pb2_grpc
import grpc
from concurrent import futures
import time
class ServerGreeter(data_pb2_grpc.dataServicer):
def serving(self, request, context):
print('serving:', request.cmd)
f = open('./a.jpg', 'rb')
img_64 = base64.b64encode(f.read())
f.close()
return data_pb2.data_reply(values=img_64)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
data_pb2_grpc.add_dataServicer_to_server(ServerGreeter(), server)
server.add_insecure_port('[::]:5001')
server.start()
try:
while True:
time.sleep(60 * 60 * 24)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
data_client.py:
import data_pb2
import data_pb2_grpc
import grpc
def run():
channel = grpc.insecure_channel('127.0.0.1:5001')
stub = data_pb2_grpc.dataStub(channel)
response = stub.serving(data_pb2.data_request(cmd='abc'))
imgf = base64.b64decode(response.values)
f = open('./b.jpg', 'wb')
f.write(imgf)
f.close()
if __name__ == '__main__':
run()
阅读(2091) | 评论(0) | 转发(0) |