-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.py
84 lines (68 loc) · 2.46 KB
/
service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import time
from concurrent import futures
import grpc
import hello_bilibili_pb2 as pb2
import hello_bilibili_pb2_grpc as pb2_grpc
class Bilibili(pb2_grpc.BibiliServicer):
def HelloDewei(self, request, context):
name = request.name
age = request.age
if not name or not age:
context.set_details('fuck xxx')
context.set_code(grpc.StatusCode.DATA_LOSS)
raise context
context.set_trailing_metadata((('name', 'pig'), ('key', 'value')))
headers = context.invocation_metadata()
print(headers[0].key, headers[0].value)
result = 'my name is {}, i am {} years old'.format(name, age)
context.set_compression(grpc.Compression.Gzip)
return pb2.HelloDeweiReply(result=result)
def TestClientRecvStream(self, request, context):
index = 0
while context.is_active():
data = request.data
if data == 'close':
print('data is close, request wil cancel')
context.cancel()
time.sleep(1)
index += 1
result = 'send {} {}'.format(index, data)
yield pb2.TestClientRecvStreamResponse(
result=result
)
def TestClientSendStream(self, request_iterator, context):
index = 0
for request in request_iterator:
print(request.data, ':', index)
if index == 10:
break
index += 1
return pb2.TestClientSendStreamResponse(result='ok')
def TestTwoWayStream(self, request_iterator, context):
index = 0
for request in request_iterator:
data = request.data
if index == 3:
time.sleep(15)
index += 1
yield pb2.TestTwoWayStreamResponse(result='service send client {}'.format(data))
def run():
grpc_server = grpc.server(
futures.ThreadPoolExecutor(max_workers=4),
compression=grpc.Compression.Gzip,
options=[
('grpc.max_send_message_length', 50 * 1024 * 1024),
('grpc.max_receive_message_length', 50 * 1024 * 1024)
]
)
pb2_grpc.add_BibiliServicer_to_server(Bilibili(), 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()