Skip to content

Instantly share code, notes, and snippets.

@carlopires
Created February 4, 2019 20:39
Show Gist options
  • Save carlopires/39886804e5c499024ef7b3a870b2a999 to your computer and use it in GitHub Desktop.
Save carlopires/39886804e5c499024ef7b3a870b2a999 to your computer and use it in GitHub Desktop.
Trio echo client and server example
import trio
async def test_client(value):
stream = await trio.open_tcp_stream('127.0.0.1', 8000)
async with stream:
await stream.send_all(value)
return await stream.receive_some(4096)
async def start_server(**kwargs):
async def _echo_handler(stream):
while 1:
data = await stream.receive_some(4096)
if not data:
break
await stream.send_all(data)
await trio.serve_tcp(_echo_handler, 8000, host='127.0.0.1', **kwargs)
async def main():
async with trio.open_nursery() as nursery:
await nursery.start(start_server)
assert await test_client(b'test') == b'test'
nursery.cancel_scope.cancel()
if __name__ == '__main__':
trio.run(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment