我可以使用 python 客户端和服务器进行通信,但与 php 客户端混淆。我对 protobufers 感到困惑,一个解释整个过程的小程序会非常有帮助。
我浏览了许多文档,但仍然对实际流程感到非常困惑。
计算器.proto
syntax = "proto3";
message Request {
int32 num1 = 1;
int32 num2 = 2;
}
message Response{
int32 result = 1;
}
service Calculator {
rpc Sum(Request) returns (Response) {}
}
计算器.py
def sum(x1,x2):
y= x1+x2
return y
服务器.py
import grpc
from concurrent import futures
import time
# import the generated classes
import calculator_pb2
import calculator_pb2_grpc
# import the original calculator.py
import calculator
# create a class to define the server functions, derived from
# calculator_pb2_grpc.CalculatorServicer
class CalculatorServicer(calculator_pb2_grpc.CalculatorServicer):
# calculator.sum is exposed here
def Sum(self, request, context):
response = calculator_pb2.Response()
response.result = calculator.sum(request.num1,request.num2)
print 'Result:',response.result
return response
# create a gRPC server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
# use the generated function `add_CalculatorServicer_to_server`
# to add the defined class to the server
calculator_pb2_grpc.add_CalculatorServicer_to_server(
CalculatorServicer(), server)
# listen on port 50051
print('Starting server. Listening on port 50051.')
server.add_insecure_port('[::]:50051')
server.start()
# since server.start() will not block,
# a sleep-loop is added to keep alive
try:
while True:
time.sleep(86400)
except KeyboardInterrupt:
server.stop(0)
客户端.py
import grpc
# import the generated classes
import calculator_pb2
import calculator_pb2_grpc
# open a gRPC channel
channel = grpc.insecure_channel('localhost:50051')
# create a stub (client)
stub = calculator_pb2_grpc.CalculatorStub(channel)
while True:
try:
# create a valid request message
numbers = calculator_pb2.Request(num1=int(input("Enter number1: ")),num2=int(input("Enter number2: ")))
# make the call
response = stub.Sum(numbers)
# print 'Result:',response.result
except KeyboardInterrupt:
print("KeyboardInterrupt")
channel.unsubscribe(close)
exit()
此设置在服务器(python)中返回两个数字的加法。我想要与 python 作为服务器和 php 作为客户端的相同功能。