This repository was archived by the owner on Jan 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
71 lines (57 loc) · 1.69 KB
/
app.py
File metadata and controls
71 lines (57 loc) · 1.69 KB
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
import asyncio
import grpclib
from grpclib.client import Channel
from grpclib.server import Server
from grpclib.utils import graceful_exit
from protobuf_out.ping_service_grpclib import MyServiceBase, MyServiceStub
from protobuf_out.ping_service_pb import PingRequest, PingResponse
HOST = 'localhost'
PORT = 5051
class MyService(MyServiceBase):
async def ping(self, stream: grpclib.server.Stream):
request: PingRequest = await stream.recv_message()
counter = request.counter + 1
print(f'[Server]: {counter}')
await stream.send_message(
PingResponse(
status=PingResponse.Status.OK,
counter=counter,
)
)
async def create_client(
server_started_event: asyncio.Event
):
channel = Channel(
host=HOST,
port=PORT
)
stub = MyServiceStub(channel)
counter = 0
# explicitly wait for server start
await server_started_event.wait()
try:
while True:
print(f'[Client]: {counter}')
response: PingResponse = await stub.ping(
PingRequest(counter=counter)
)
counter = response.counter + 1
await asyncio.sleep(1)
finally:
channel.close()
async def main():
server = Server([MyService()])
server_started_event = asyncio.Event()
asyncio.create_task(
create_client(server_started_event)
)
with graceful_exit([server]):
await server.start(
host=HOST,
port=PORT,
)
server_started_event.set()
print(f'Serving on {HOST}:{PORT}')
await server.wait_closed()
if __name__ == '__main__':
asyncio.run(main())