run stdin reading in its own thread to no block the event loop
This commit is contained in:
parent
9123760191
commit
b3e2e6d8ad
17
chat.py
17
chat.py
|
@ -1,13 +1,17 @@
|
|||
#!/bin/env python3
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
import click
|
||||
|
||||
from libp2p.libp2p import Libp2p
|
||||
from network.multiaddr import MultiAddr
|
||||
|
||||
|
||||
# TODO: change once muxed_connection supports extracting protocol id from messages
|
||||
PROTOCOL_ID = '/echo/1.0.0'
|
||||
|
||||
|
||||
async def read_data(stream):
|
||||
while True:
|
||||
read_string = (await stream.read()).decode()
|
||||
|
@ -18,13 +22,15 @@ async def read_data(stream):
|
|||
if read_string != "\n":
|
||||
# Green console colour: \x1b[32m
|
||||
# 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):
|
||||
while True:
|
||||
s = input('> ')
|
||||
await stream.write(s.encode())
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
while True:
|
||||
line = await loop.run_in_executor(None, sys.stdin.readline)
|
||||
await stream.write(line.encode())
|
||||
|
||||
|
||||
async def run(port, destination):
|
||||
|
@ -50,7 +56,6 @@ async def run(port, destination):
|
|||
if not 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("You can replace 127.0.0.1 with public IP as well.")
|
||||
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(write_data(stream))
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.option('--port', help='source port number', default=8000)
|
||||
@click.option('--destination', '-d', help="Destination multiaddr string")
|
||||
|
@ -97,5 +103,6 @@ def main(port, destination, help):
|
|||
finally:
|
||||
loop.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
Loading…
Reference in New Issue
Block a user