安装
生成
--python_out --pyi_out --grpc_python_out 对应生成的ticket_pb2.py ticket_pb2.pyi ticket_pb2.pyi三个文件对应路径
服务端
import grpc
from concurrent import futures
import logging
import ticket_pb2,ticket_pb2_grpc
class Ticket(ticket_pb2_grpc.TicketServicer):
# 重写原先proto文件方法
def QueryTicket(self, request, context):
return ticket_pb2.QueryReply(num=100)
def serve():
with open('server.key','rb') as f:
private_key = f.read()
with open('server.crt','rb') as f:
certificate_chain = f.read()
server_credentials = grpc.ssl_server_credentials(
((private_key, certificate_chain,),))
port = '50051'
# 启用ssl
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
ticket_pb2_grpc.add_TicketServicer_to_server(Ticket(), server)
server.add_secure_port('[::]:' + port,server_credentials)
server.start()
print("Server started, listening on " + port)
server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig()
serve()
客户端
创建一个客户端于服务端通信
import grpc
import ticket_pb2,ticket_pb2_grpc
from src.google.protobuf.struct_pb2 import Struct
_HOST = 'localhost'
_PORT = '50051'
def run():
with open('server.crt', 'rb') as f:
trusted_certs = f.read()
credentials = grpc.ssl_channel_credentials(root_certificates=trusted_certs)
options = (('grpc.ssl_target_name_override','WLYNC',),)
with grpc.secure_channel((_HOST+':'+_PORT), credentials, options = options) as channel:
stub = ticket_pb2_grpc.TicketStub(channel)
response:ticket_pb2.QueryReply = stub.QueryTicket(ticket_pb2.QueryRequest(id="1"))
print(f"票数: {response.num}")
if __name__ == '__main__':
run()
运行效果
启动服务端
启动客户端