Skip to content

Commit

Permalink
Update README example to async code (#331)
Browse files Browse the repository at this point in the history
  • Loading branch information
LasseBlaauwbroek committed Oct 12, 2023
1 parent 941f018 commit ae96512
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ if __name__ == '__main__':
Also, pycapnp has gained RPC features that include pipelining and a promise style API. Refer to the calculator example in the examples directory for a much better demonstration:

```python
import asyncio
import capnp
import socket

Expand All @@ -185,31 +186,33 @@ class Server(test_capability_capnp.TestInterface.Server):
def __init__(self, val=1):
self.val = val

def foo(self, i, j, **kwargs):
async def foo(self, i, j, **kwargs):
return str(i * 5 + self.val)


def server(write_end):
server = capnp.TwoPartyServer(write_end, bootstrap=Server(100))


def client(read_end):
async def client(read_end):
client = capnp.TwoPartyClient(read_end)

cap = client.bootstrap()
cap = cap.cast_as(test_capability_capnp.TestInterface)

remote = cap.foo(i=5)
response = remote.wait()
response = await remote

assert response.x == '125'


if __name__ == '__main__':
read_end, write_end = socket.socketpair(socket.AF_UNIX)
async def main():
client_end, server_end = socket.socketpair(socket.AF_UNIX)
# This is a toy example using socketpair.
# In real situations, you can use any socket.

server(write_end)
client(read_end)
client_end = await capnp.AsyncIoStream.create_connection(sock=client_end)
server_end = await capnp.AsyncIoStream.create_connection(sock=server_end)

_ = capnp.TwoPartyServer(server_end, bootstrap=Server(100))
await client(client_end)


if __name__ == '__main__':
asyncio.run(capnp.run(main()))
```

0 comments on commit ae96512

Please sign in to comment.