-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
66 lines (44 loc) · 1.23 KB
/
server.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
"use strict";
/*!
* WebSocket Realtime Transport - Server
* Copyright(c) 2013 Owen Barnes <[email protected]>
* MIT Licensed
*/
var WebSocketServer = require('ws').Server;
module.exports = function(options) {
options = options || {};
var clientCount = 0;
var clients = {};
return function(server) {
var ws = new WebSocketServer({port: server.port});
ws.on('connection', function(socket) {
// Assign SocketID
socket.id = String(++clientCount);
clients[socket.id] = socket;
server.events.emit('connect', socket.id);
socket.on('message', function(message) {
var request = {
message: message,
transport: 'ws',
socketId: socket.id,
clientIp: socket.upgradeReq.headers.host.split(':')[0]
};
server.process(request);
});
socket.on('close', function() {
server.events.emit('disconnect', socket.id);
delete clients[socket.id];
});
});
return {
sendToSocketId: function(socketId, msg) {
clients[socketId].send(msg);
},
broadcast: function(msg){
for (var socketId in clients) {
clients[socketId].send(msg);
}
}
};
};
};