-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathasync_client.py
executable file
·55 lines (39 loc) · 1.57 KB
/
async_client.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
#!/usr/bin/env python3
import asyncio
import argparse
import time
import capnp
import thread_capnp
def parse_args():
parser = argparse.ArgumentParser(
usage="Connects to the Example thread server at the given address and does some RPCs"
)
parser.add_argument("host", help="HOST:PORT")
return parser.parse_args()
class StatusSubscriber(thread_capnp.Example.StatusSubscriber.Server):
"""An implementation of the StatusSubscriber interface"""
async def status(self, value, **kwargs):
print("status: {}".format(time.time()))
async def main(host):
host, port = host.split(":")
connection = await capnp.AsyncIoStream.create_connection(host=host, port=port)
client = capnp.TwoPartyClient(connection)
cap = client.bootstrap().cast_as(thread_capnp.Example)
# Start background task for subscriber
task = asyncio.ensure_future(cap.subscribeStatus(StatusSubscriber()))
# Run blocking tasks
print("main: {}".format(time.time()))
await cap.longRunning()
print("main: {}".format(time.time()))
await cap.longRunning()
print("main: {}".format(time.time()))
await cap.longRunning()
print("main: {}".format(time.time()))
task.cancel()
if __name__ == "__main__":
args = parse_args()
asyncio.run(capnp.run(main(args.host)))
# Test that we can run multiple asyncio loops in sequence. This is particularly tricky, because
# main contains a background task that we never cancel. The entire loop gets cleaned up anyways,
# and we can start a new loop.
asyncio.run(capnp.run(main(args.host)))