py-libp2p/examples/chat/chat.py

95 lines
3.1 KiB
Python
Raw Normal View History

2018-11-20 00:29:48 +08:00
import asyncio
import sys
2019-02-11 09:52:05 +08:00
import urllib.request
2018-11-20 00:29:48 +08:00
import click
import multiaddr
from libp2p import new_node
from libp2p.peer.peerinfo import info_from_p2p_addr
2018-11-19 00:22:56 +08:00
PROTOCOL_ID = '/chat/1.0.0'
2018-11-19 00:22:56 +08:00
2018-11-19 00:22:56 +08:00
async def read_data(stream):
while True:
read_string = await stream.read()
if read_string is not None:
read_string = read_string.decode()
if read_string != "\n":
# Green console colour: \x1b[32m
# Reset console colour: \x1b[0m
print("\x1b[32m %s\x1b[0m " % read_string, end="")
2018-11-19 00:22:56 +08:00
async def write_data(stream):
loop = asyncio.get_event_loop()
while True:
line = await loop.run_in_executor(None, sys.stdin.readline)
await stream.write(line.encode())
2018-11-19 00:22:56 +08:00
async def run(port, destination):
2019-02-11 09:52:05 +08:00
external_ip = urllib.request.urlopen(
'https://v4.ident.me/').read().decode('utf8')
2019-04-19 03:56:02 +08:00
transport_opt = "/ip4/%s/tcp/%s" % (external_ip, port)
2019-02-11 09:52:05 +08:00
host = await new_node(
2019-04-19 03:56:02 +08:00
transport_opt=[transport_opt])
await host.get_network().listen(multiaddr.Multiaddr(transport_opt))
if not destination: # its the server
2018-11-19 00:22:56 +08:00
async def stream_handler(stream):
asyncio.ensure_future(read_data(stream))
asyncio.ensure_future(write_data(stream))
host.set_stream_handler(PROTOCOL_ID, stream_handler)
if not port:
raise RuntimeError("was not able to find the actual local port")
2019-02-11 09:52:05 +08:00
print("Run './examples/chat/chat.py -p %s -d /ip4/%s/tcp/%s/p2p/%s' on another console.\n" %
2019-04-19 03:56:02 +08:00
(int(port) + 1, external_ip, port, host.get_id().pretty()))
2018-11-19 00:22:56 +08:00
print("\nWaiting for incoming connection\n\n")
else: # its the client
m = multiaddr.Multiaddr(destination)
info = info_from_p2p_addr(m)
# Associate the peer with local ip address
await host.connect(info)
2018-11-19 00:22:56 +08:00
# Start a stream with the destination.
# Multiaddress of the destination peer is fetched from the peerstore using 'peerId'.
stream = await host.new_stream(info.peer_id, [PROTOCOL_ID])
2018-11-19 00:22:56 +08:00
asyncio.ensure_future(read_data(stream))
asyncio.ensure_future(write_data(stream))
print("Connected to peer %s" % info.addrs[0])
2018-11-19 00:22:56 +08:00
2018-11-19 00:22:56 +08:00
@click.command()
@click.option('--port', '-p', help='source port number', default=8000)
2018-11-19 00:22:56 +08:00
@click.option('--destination', '-d', help="Destination multiaddr string")
@click.option('--help', is_flag=True, default=False, help='display help')
# @click.option('--debug', is_flag=True, default=False, help='Debug generates the same node ID on every execution')
def main(port, destination, help):
if help:
print("This program demonstrates a simple p2p chat application using libp2p\n\n")
print("Usage: Run './chat -p <SOURCE_PORT>' where <SOURCE_PORT> can be any port number.")
print("Now run './chat -p <PORT> -d <MULTIADDR>' where <MULTIADDR> is multiaddress of previous listener host.")
2018-11-19 00:22:56 +08:00
return
loop = asyncio.get_event_loop()
try:
asyncio.ensure_future(run(port, destination))
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
loop.close()
2018-11-19 00:22:56 +08:00
if __name__ == '__main__':
main()