#hello_bilibili.proto
syntax = "proto3";
package test;
service Bibili {
rpc HelloDewei(HelloDeweiReq) returns (HelloDeweiReply){}
rpc HelloTest(stream HelloTestReq) returns (stream HelloTestReply){}
rpc TestClientRecvStream(TestClientRecvStreamRequest) returns (stream TestClientRecvStreamResponse){}
rpc TestClientSendStream(stream TestClientSendStreamRequest) returns (TestClientSendStreamResponse){}
}
message HelloDeweiReq {
string name = 1;
int32 age = 2;
}
message HelloDeweiReply {
string result =1;
}
message HelloTestReq {
string name = 1;
int64 age = 2;
repeated string data = 3;
map<string,HelloTestReqnumbervalue> number = 4;
}
message HelloTestReqnumbervalue {
string name = 1;
int64 age = 2;
bool is_active = 3;
}
message HelloTestReply {
string result =1;
}
message TestClientRecvStreamRequest {
string data =1;
}
message TestClientRecvStreamResponse {
string result =1;
}
message TestClientSendStreamRequest {
string data =1;
}
message TestClientSendStreamResponse {
string result =1;
}
#client.py
#coding:utf-8
import time
import random
import grpc
import hello_bilibili_pb2 as pb2
import hello_bilibili_pb2_grpc as pb2_grpc
def test():
while 1:
time.sleep(1)
data = str(random.random())
yield pb2.TestClientSendStreamRequest(data=data)
def run():
conn = grpc.insecure_channel("127.0.0.1:5000")
client = pb2_grpc.BibiliStub(channel=conn)
# response = client.HelloDewei(pb2.HelloDeweiReq(
# name='dewei',
# age = 28
# ))
# print(response.result)
# response = client.TestClientRecvStream(pb2.TestClientRecvStreamRequest(
# data='dewei',
#
# ))
# for item in response:
# print(item.result)
response = client.TestClientSendStream(test())
print(response.result)
if __name__ == '__main__':
run()
#service.py
#coding:utf-8
import time
import grpc
import hello_bilibili_pb2 as pb2
import hello_bilibili_pb2_grpc as pb2_grpc
from concurrent import futures
class Bibili(pb2_grpc.BibiliServicer):
def HelloDewei(self, request, context):
name = request.name
age = request.age
result = f'my name is {name}, iam {age} years old'
return pb2.HelloDeweiReply(result=result)
def TestClientRecvStream(self,request,context):
index = 1
while context.is_active():
data = request.data
if data == "close":
context.cancel()
time.sleep(1)
index += 1
yield pb2.TestClientRecvStreamResponse(
result = "send %d %s"%(index,data)
)
def TestClientSendStream(self, request_iterator, context):
for request in request_iterator:
print(request)
return pb2.TestClientRecvStreamResponse(result='ok')
def run():
grpc_server = grpc.server(
futures.ThreadPoolExecutor(max_workers=4)
)
pb2_grpc.add_BibiliServicer_to_server(Bibili(),grpc_server)
grpc_server.add_insecure_port('0.0.0.0:5000')
print("server will start at 0.0.0.0:5000")
grpc_server.start()
try:
while 1:
time.sleep(3600)
except KeyboardInterrupt:
grpc_server.stop(0)
if __name__ == '__main__':
run()