1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
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 = [];
|