CTO要求我們內部模塊用grpc通訊,我們需要用python解析bim ifc文件,所以給一位同事寫了個python通過grpc發送接收文件的小demo。
grpc不多說了,python安裝也不說了,用的版本是3.8.3,操作系統是Windows10,python的IDE用PyCharm。
1、pip安裝依賴和工具
pip install grpcio pip install protobuf pip install grpcio_tools
2、編寫proto
syntax = "proto3"; package helloworld; service FileService { rpc Upload(FileRequest) returns (FileReply) {} } message FileRequest { bytes file = 1; string name = 2; } message FileReply { string msg = 1; }
3、使用工具生成代碼
windows命令行進入proto文件目錄下,運行
python -m grpc_tools.protoc -I. --python_out=./ --grpc_python_out=./ ./helloworld.proto
4、編寫服務端hello_server.py
from concurrent import futures import grpc import helloworld_pb2 import helloworld_pb2_grpc MAX_MESSAGE_LENGTH = 256 * 1024 * 1024 # 設置grpc最大可接受的文件大小 256M class FileService(helloworld_pb2_grpc.FileServiceServicer): def Upload(self, request, context): print("received..") file_data = request.file # 接收到的文件 file_name = request.name # 接收到的文件名稱 print(file_name) f = open("D:\\" + file_name, "wb") # 把傳來的文件寫入本地磁盤 f.write(file_data) # 寫文件 f.close() # 關閉IO # 這里我們會處理解析ifc文件,不寫了 return helloworld_pb2.FileReply(msg='ok') def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), options=[('grpc.max_send_message_length', MAX_MESSAGE_LENGTH), ('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH), ]) helloworld_pb2_grpc.add_FileServiceServicer_to_server(FileService(), server) server.add_insecure_port('[::]:50051') print('listen on 50051') server.start() server.wait_for_termination() if __name__ == '__main__': serve()
5、編寫客戶端hello_server.py
from __future__ import print_function import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): with grpc.insecure_channel('localhost:50051') as channel: path = 'D:\\yazf.ifc' # 要發送到服務端的本地ifc文件 print(path) f = open(path, 'rb') # 讀取 data = f.read() f.close() # 調用rpc stub = helloworld_pb2_grpc.FileServiceStub(channel) response = stub.Upload(helloworld_pb2.FileRequest(file=data, name='test.ifc')) print("File client received: " + response.msg) if __name__ == '__main__': run()
6、運行測試
先運行hello_server,再運行hello_client,正常情況下目錄下會多一個test.ifc文件。