-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
77 lines (65 loc) · 1.97 KB
/
server.js
File metadata and controls
77 lines (65 loc) · 1.97 KB
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
var
_ = require('lodash'),
io = require('socket.io'),
express = require('express'),
port = 9222,
app = express(),
hosts = {},
server = null;
// Trust X-Forwarded-* header fields
app.enable('trust proxy');
// Initialize server & socket.io
server = app.listen(port);
io = io.listen(server, {log: false});
// Connection handlers
io.sockets.on('connection', function(socket) {
/**
* Listen on request to register a client.
*/
socket.on('register', function(msg) {
// Register peer client as ready
if (msg.ready && !(socket.id in hosts)) {
hosts[socket.id] = {
socket: socket,
client_id: socket.id
};
// Build registration object
hosts[socket.id].init = {
client_id: socket.id
};
// Send registration to client
socket.emit('ready', hosts[socket.id].init);
}
// Alert new peers
for (var socket_id in hosts) {
hosts[socket_id].socket.emit('peer', {peer_id: socket.id});
}
});
/**
* Listen on request to deregister client.
*/
socket.on('disconnect', function() {
delete hosts[socket.id];
});
/**
* Listen on request to send data message to target peer.
*
* @param messageObject {Object}
* @param messageObject.peer_id Socket ID of target peer to send message to
* @param messageObject.client_id Socket ID of peer sending the message
* @param messageObject.handler_id Name of listening 'onmessage' callback
*/
socket.on('MessageToPeer', function( messageObject ) {
var
target_peer = null,
handler = messageObject.handler_id;
// Send message to peer
if (messageObject.peer_id in hosts) {
target_peer = hosts[messageObject.peer_id].socket;
target_peer.emit(handler, _.extend(messageObject, {
client_id: messageObject.peer_id,
peer_id: messageObject.client_id
}));
}
});
});