/
socket.js
54 lines (39 loc) · 1.18 KB
/
socket.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
var http = require('http'),
sockjs = require('sockjs'),
server = http.createServer(),
webSockets,
buffer = [],
clients = {};
function whisper (id, message) {
if ( !clients[id] ) return;
clients[id].write( JSON.stringify(message) );
}
function broadcast (message, exclude) {
for ( var i in clients ) {
if ( i != exclude ) clients[i].write( JSON.stringify(message) );
}
}
function onConnection (conn) {
clients[conn.id] = conn;
broadcast({ type: 'newUser' }, conn.id);
whisper(conn.id, { type: 'history', message: buffer, id: conn.id });
conn.on('data', function onDataCB (data) {
data = JSON.parse(data);
if ( data.type == 'text' ) {
if ( !data.message ) return;
data.message = data.message.substr(0, 128);
if ( buffer.length > 15 ) buffer.shift();
buffer.push(data.message);
broadcast({ type: 'message', message: data.message, id: conn.id });
}
// TODO: add user name
});
conn.on('close', function onCloseCB () {
delete clients[conn.id];
broadcast({ type: 'userLeft' });
});
}
webSockets = sockjs.createServer();
webSockets.on('connection', onConnection);
webSockets.installHandlers(server, { prefix:'/echo' } );
server.listen(9999, '0.0.0.0');