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(''); } GLOBAL = {} GLOBAL.lobby_id = genRanHex(6); console.log("lobby_id:" + GLOBAL.lobby_id); 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; }); console.log("poo:" + poo); console.log("Peer:",peer) var poe = peer.on('error',function(err){ console.log("Error on peer:") console.log(err); GLOBAL.error = err; }); GLOBAL.peer = peer; GLOBAL.peer_id = () => peer_id; GLOBAL.get_error = () => error; GLOBAL.connections = {}; GLOBAL["get_message"] = function(){ if(GLOBAL.message_queue.length >= 1){ return GLOBAL.message_queue.shift(); }else{ return null; } } GLOBAL["send_message"] = function(who, data){ if(GLOBAL.connections[who]._open){ GLOBAL.connections[who].send(data); return true } return false; } GLOBAL["broadcast"] = function(data){ console.log("Server broadcasting message:") console.log(data) for(var peerid in GLOBAL.connections){ if (GLOBAL.connections[peerid]._open){ GLOBAL.connections[peerid].send(data); } } return true; } GLOBAL["get_peers"] = function() { return GLOBAL.connections; } GLOBAL.message_queue = [];