forked from ryscheng/CollaborativeWebDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeer.js
87 lines (84 loc) · 2.31 KB
/
peer.js
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
81
82
83
84
85
86
87
// Adapted from the tornado webchat demo.
var server = {
socket: null,
subscribers: [],
write: function(obj) {
if (!this.socket) {
return false;
}
return this.socket.send(JSON.stringify({"payload": obj}));
},
start: function() {
var url = "ws://" + location.host + "/message";
if (!window.WebSocket) {
return false;
}
this.socket = new WebSocket(url);
var that = this;
this.socket.onmessage = function(event) {
var msg = JSON.parse(event.data);
for (var i = 0; i < that.subscribers.length; i++) {
that.subscribers[i](msg);
}
}
return true;
}
};
var node = {
edges:{},
MAX_EDGES: 20,
onServerMessage: function(msg) {
if (msg['from'] === 0)
{
if (msg['id'] && !this.id) {
// Registration complete.
this.id = msg['id'];
log.write("Registered with server as " + this.id);
// todo: consider announces on a timer or when deficient degree.
server.write({
event:'announce'
});
}
} else if (msg['from'] && msg['from'] != this.id) {
if (this.edges[msg['from']]) {
this.edges[msg['from']].processSignalingMessage(msg['msg']);
// Continue signalling a peer.
} else if (msg['event'] && msg['event'] == 'announce') {
// Initiate connection to a new peer.
this.maybeConnect_(msg['from']);
} else if (msg['event'] && msg['event'] == 'decline') {
if (this.edges[msg['from']]) {
this.edges[msg['from']].close();
delete this.edges[msg['from']];
}
} else if (msg['msg'] && !this.full()) {
this.maybeConnect_(msg['from']);
this.edges[msg['from']].processSignalingMessage(msg['msg']);
} else {
server.write({to:msg['from'], event:'decline'});
}
}
},
full: function() {
var edge_num = 0;
for (var i in this.edges) {
if(this.edges.hasOwnProperty(i)) {
edge_num++;
}
}
return (edge_num >= this.MAX_EDGES);
},
maybeConnect_:function(id) {
if (!this.full()) {
// todo: true channel setup integration.
var pc = new webkitDeprecatedPeerConnection("STUN stun.l.google.com:19302", this.send_.bind(this, id));
this.edges[id] = pc;
}
},
send_:function(id, msg) {
server.write({
to:id,
msg:msg
})
}
};