-
Notifications
You must be signed in to change notification settings - Fork 32
/
peer.html
70 lines (65 loc) · 2.07 KB
/
peer.html
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
<html>
<style>
#messages {
width: 100%;
}
</style>
<body>
Log Messages:
<div>
<textarea id='messages' rows=20></textarea>
</div>
<script src="http://cdn.peerjs.com/0.3/peer.js"></script>
<script src="jquery-2.1.3.min.js"></script>
<script>
var messages = document.getElementById('messages');
function log() {
var msg = Array.prototype.slice.call(arguments, 0).join(' ');
messages.innerHTML += msg + "\n";
messages.scrollTop = messages.scrollHeight;
}
var my_id = null;
var connections = {};
var peer = new Peer({host: location.hostname,
port: location.port,
path: '/api'});
peer.on('open', function(id) {
log('my ID:', id);
my_id = id;
// Load the peer list and connect
jQuery.getJSON('/peers', function (peers) {
log("Peer list:", peers);
$.each(peers, function (idx, peer_id) {
// If it is us, or we are already connected, ignore
if (peer_id === my_id) return true;
if (peer_id in connections) return true;
log("Connecting to:", peer_id);
var conn = peer.connect(peer_id);
connections[peer_id] = conn;
conn.on('data', function(data) {
log("received from " + conn.peer + ": " + data);
});
conn.on('close', function(data) {
log("Connection closed:" + conn.peer);
delete connections[peer_id];
});
});
});
});
peer.on('error', function(e) {
log('peer error:', e);
});
peer.on('connection', function(conn) {
log("got connection from:", conn.peer);
connections[conn.peer] = conn;
conn.on('data', function(data) {
log("received from " + conn.peer + ": " + data);
});
conn.on('close', function(data) {
log("Connection closed:" + conn.peer);
delete connections[conn.peer];
});
});
</script>
</body>
</html>