Updated examples to automatically use random port (#661)

* updated examples to automatically use random port

* Refactor examples to use shared utils for port selection (#1)

---------

Co-authored-by: acul71 <34693171+acul71@users.noreply.github.com>
This commit is contained in:
Abhinav Agarwalla
2025-06-10 00:29:11 +05:30
committed by GitHub
parent c83fc1582d
commit 4e9fa87477
6 changed files with 24 additions and 60 deletions

View File

@ -30,7 +30,6 @@ async def _echo_stream_handler(stream: INetStream) -> None:
async def run(port: int, destination: str, seed: int | None = None) -> None:
localhost_ip = "127.0.0.1"
listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}")
if seed:
@ -53,8 +52,8 @@ async def run(port: int, destination: str, seed: int | None = None) -> None:
print(
"Run this from the same folder in another console:\n\n"
f"echo-demo -p {int(port) + 1} "
f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host.get_id().pretty()}\n"
f"echo-demo "
f"-d {host.get_addrs()[0]}\n"
)
print("Waiting for incoming connections...")
await trio.sleep_forever()
@ -73,6 +72,7 @@ async def run(port: int, destination: str, seed: int | None = None) -> None:
msg = b"hi, there!\n"
await stream.write(msg)
# TODO: check why the stream is closed after the first write ???
# Notify the other side about EOF
await stream.close()
response = await stream.read()
@ -94,9 +94,7 @@ def main() -> None:
"/ip4/127.0.0.1/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q"
)
parser = argparse.ArgumentParser(description=description)
parser.add_argument(
"-p", "--port", default=8000, type=int, help="source port number"
)
parser.add_argument("-p", "--port", default=0, type=int, help="source port number")
parser.add_argument(
"-d",
"--destination",
@ -110,10 +108,6 @@ def main() -> None:
help="provide a seed to the random number generator (e.g. to fix peer IDs across runs)", # noqa: E501
)
args = parser.parse_args()
if not args.port:
raise RuntimeError("was not able to determine a local port")
try:
trio.run(run, args.port, args.destination, args.seed)
except KeyboardInterrupt: