Add a localhost option and fix the printed example to run another peer

This commit is contained in:
Alex Stokes 2019-08-02 10:22:15 -07:00
parent 430b4e2f89
commit c8d175b373
No known key found for this signature in database
GPG Key ID: 51CE1721B245C086

View File

@ -31,9 +31,12 @@ async def write_data(stream):
await stream.write(line.encode()) await stream.write(line.encode())
async def run(port, destination): async def run(port, destination, localhost):
external_ip = urllib.request.urlopen("https://v4.ident.me/").read().decode("utf8") if localhost:
transport_opt = "/ip4/%s/tcp/%s" % (external_ip, port) ip = "127.0.0.1"
else:
ip = urllib.request.urlopen("https://v4.ident.me/").read().decode("utf8")
transport_opt = f"/ip4/{ip}/tcp/{port}"
host = await new_node(transport_opt=[transport_opt]) host = await new_node(transport_opt=[transport_opt])
await host.get_network().listen(multiaddr.Multiaddr(transport_opt)) await host.get_network().listen(multiaddr.Multiaddr(transport_opt))
@ -46,10 +49,12 @@ async def run(port, destination):
host.set_stream_handler(PROTOCOL_ID, stream_handler) host.set_stream_handler(PROTOCOL_ID, stream_handler)
localhost_opt = " --localhost" if localhost else ""
print( print(
"Run './examples/chat/chat.py -p %s -d /ip4/%s/tcp/%s/p2p/%s' on another console.\n" f"Run 'python ./examples/chat/chat.py"
% (int(port) + 1, external_ip, port, host.get_id().pretty()) + localhost_opt
+ f" -p {int(port) + 1} -d /ip4/{ip}/tcp/{port}/p2p/{host.get_id().pretty()}' on another console.\n"
) )
print("\nWaiting for incoming connection\n\n") print("\nWaiting for incoming connection\n\n")
@ -93,6 +98,13 @@ def main():
type=str, type=str,
help=f"destination multiaddr string, e.g. {example_maddr}", help=f"destination multiaddr string, e.g. {example_maddr}",
) )
parser.add_argument(
"-l",
"--localhost",
dest="localhost",
action="store_true",
help="flag indicating if localhost should be used or an external IP",
)
args = parser.parse_args() args = parser.parse_args()
if not args.port: if not args.port:
@ -100,7 +112,7 @@ def main():
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
try: try:
asyncio.ensure_future(run(args.port, args.destination)) asyncio.ensure_future(run(args.port, args.destination, args.localhost))
loop.run_forever() loop.run_forever()
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass