From 7246016b8bee686e4cf37484abafbb9814588a12 Mon Sep 17 00:00:00 2001 From: John Alanbrook Date: Fri, 23 May 2025 14:23:52 -0500 Subject: [PATCH] example nat --- examples/nat.js | 29 +++++++++++++++++++++++++++++ examples/nat_client.js | 22 ++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 examples/nat.js create mode 100644 examples/nat_client.js diff --git a/examples/nat.js b/examples/nat.js new file mode 100644 index 00000000..a8779321 --- /dev/null +++ b/examples/nat.js @@ -0,0 +1,29 @@ +// NAT Punchthrough Server +// This server helps two chess clients find each other through NAT +// The server coordinates the punchthrough by having both clients +// connect to each other simultaneously + +var json = use('json'); +var waiting_client = null; +var match_id = 0; + +$_.portal(e => { + console.log("NAT server: received connection request"); + + if (!is_actor(e.actor)) + send(e, {reason: "Must provide the actor you want to connect."}); + + if (waiting_client) { + console.log(`sending out messages! to ${json.encode(e.actor)} and ${json.encode(waiting_client.actor)}`) + send(waiting_client, e.actor) + send(e, waiting_client.actor) + + waiting_client = undefined + + return + } + + waiting_client = e + + console.log(`actor ${json.encode(e.actor)} is waiting ...`) +}, 4000); diff --git a/examples/nat_client.js b/examples/nat_client.js new file mode 100644 index 00000000..00434e5c --- /dev/null +++ b/examples/nat_client.js @@ -0,0 +1,22 @@ +console.log(`nat client starting`) + +$_.contact((actor, reason) => { + if (actor) { + console.log(`trying to message ${json.encode(actor)}`) + send(actor, {type:"greet"}) + } else { + console.log(json.encode(reason)) + } +}, { + address: "108.210.60.32", // NAT server's public IP + port: 4000, + actor: $_ +}) + +$_.receiver(e => { + switch(e.type) { + case 'greet': + console.log(`hello!`) + break + } +}) \ No newline at end of file