run stdin reading in its own thread to no block the event loop

This commit is contained in:
Christophe de Carvalho Pereira Martins 2018-11-19 08:58:07 +01:00
parent 9123760191
commit b3e2e6d8ad
No known key found for this signature in database
GPG Key ID: EFEE139F5CCB06C2

19
chat.py
View File

@ -1,13 +1,17 @@
#!/bin/env python3 #!/bin/env python3
import asyncio import asyncio
import sys
import click import click
from libp2p.libp2p import Libp2p from libp2p.libp2p import Libp2p
from network.multiaddr import MultiAddr from network.multiaddr import MultiAddr
# TODO: change once muxed_connection supports extracting protocol id from messages # TODO: change once muxed_connection supports extracting protocol id from messages
PROTOCOL_ID = '/echo/1.0.0' PROTOCOL_ID = '/echo/1.0.0'
async def read_data(stream): async def read_data(stream):
while True: while True:
read_string = (await stream.read()).decode() read_string = (await stream.read()).decode()
@ -18,13 +22,15 @@ async def read_data(stream):
if read_string != "\n": if read_string != "\n":
# Green console colour: \x1b[32m # Green console colour: \x1b[32m
# Reset console colour: \x1b[0m # Reset console colour: \x1b[0m
print("\x1b[32m%s\x1b[0m> " % read_string) print("\x1b[32m%s\x1b[0m" % read_string)
async def write_data(stream): async def write_data(stream):
while True: loop = asyncio.get_event_loop()
s = input('> ')
await stream.write(s.encode())
while True:
line = await loop.run_in_executor(None, sys.stdin.readline)
await stream.write(line.encode())
async def run(port, destination): async def run(port, destination):
@ -50,8 +56,7 @@ async def run(port, destination):
if not port: if not port:
raise RuntimeError("was not able to find the actual local port") raise RuntimeError("was not able to find the actual local port")
print("Run './chat.py --port %s -d /ip4/127.0.0.1/tcp/%s/p2p/%s' on another console.\n" % (int(port)+1, port, host.get_id().pretty()))
print("Run './chat.py --port %s -d /ip4/127.0.0.1/tcp/%s/p2p/%s' on another console.\n" % (int(port)+1,port, host.get_id().pretty()))
print("You can replace 127.0.0.1 with public IP as well.") print("You can replace 127.0.0.1 with public IP as well.")
print("\nWaiting for incoming connection\n\n") print("\nWaiting for incoming connection\n\n")
@ -75,6 +80,7 @@ async def run(port, destination):
asyncio.ensure_future(read_data(stream)) asyncio.ensure_future(read_data(stream))
asyncio.ensure_future(write_data(stream)) asyncio.ensure_future(write_data(stream))
@click.command() @click.command()
@click.option('--port', help='source port number', default=8000) @click.option('--port', help='source port number', default=8000)
@click.option('--destination', '-d', help="Destination multiaddr string") @click.option('--destination', '-d', help="Destination multiaddr string")
@ -97,5 +103,6 @@ def main(port, destination, help):
finally: finally:
loop.close() loop.close()
if __name__ == '__main__': if __name__ == '__main__':
main() main()