From 00a3451004d664a5386f3750540facddc0d2686b Mon Sep 17 00:00:00 2001 From: Alexander M Pickering Date: Mon, 9 Dec 2024 21:48:17 -0600 Subject: Add a channel abstraction to use for networking --- src/js_bridge.js | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/js_bridge.js (limited to 'src/js_bridge.js') diff --git a/src/js_bridge.js b/src/js_bridge.js new file mode 100644 index 0000000..2d32739 --- /dev/null +++ b/src/js_bridge.js @@ -0,0 +1,54 @@ +var s = document.createElement('script'); +s.setAttribute('src','https://unpkg.com/peerjs@1.5.2/dist/peerjs.min.js'); +document.body.appendChild(s); +function genRanHex(size) { + return Array.apply(null,Array(size)).map(() => Math.floor(Math.random() * 16).toString(16)).join(''); +} +PEER = {} +PEER.event_queue = {} +PEER.peers = {} +PEER.message_queue = {} +PEER["create"] = function(name, options) { + var peer = new Peer(name, options) + PEER.peers[name] = peer +} +PEER["on"] = function(name, e, message) { + PEER.peers[name].on(e, function(conn) { + PEER.message_queue.push(message) + } +} +PEER["connect"] = function(name, id, options) { + PEER.peers[name].connect(id, options) +} +var peer = new Peer("ANGRY_ADVENTURE_" + GLOBAL.lobby_id, {"debug": 3}); +var peer_id = null; +var poo = peer.on('open', function(id) { + console.log('My peer ID is: ' + id); + peer.on("connection",function(conn){ + console.log("Got a connection!") + GLOBAL.connections[conn.peer] = conn + conn.send("Hello!") + GLOBAL.message_queue.push({ + "msg": "data", + "peer": conn.peer, + "data": '{"msg":"player_joined"}' + }) + conn.on("data",function(data){ + console.log("Got some data from a peer!:" + data) + GLOBAL.message_queue.push({ + "msg": "data", + "peer": conn.peer, + "data": data + }) + }) + conn.on("error",function(err){ + console.log("Error on a connection:" + err) + GLOBAL.message_queue.push({ + "msg": "error", + "peer": conn.peer, + "err": err + }) + }) + }) + GLOBAL.peer_id = id; +}); -- cgit v1.2.3-70-g09d2