-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
90 lines (72 loc) · 2.2 KB
/
index.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
88
89
90
const WebSocket = require('ws');
class WebsocketHandler
{
constructor()
{
this.port=8000;
this._websocket=null;
this._clients=[];
this._msgCount=0;
}
start()
{
setInterval(()=>
{
this.send({msg:"test"+this._msgCount++});
},1000);
const wss = new WebSocket.Server(
{
port: this.port,
perMessageDeflate: false
});
console.log('starting websocket server on port '+this.port);
wss.on('connection', function connection(websock)
{
this._clients.push(websock);
console.log('[websocket] client has connected! ('+this._clients.length+')');
this._logNumClients();
websock.on('close', function close() {
console.log('[websocket] client disconnected');
this._removeClient(websock);
}.bind(this));
websock.on('message', function incoming(message)
{
console.log('received: ', message);
});
websock.on('error', function(error)
{
if(error != null)
{
console.log('error: %s', error);
this._removeClient(websock);
websock.close();
websock._socket.destroy();
Client.splice(findClient(websock.upgradeReq.url));
}
}.bind(this));
}.bind(this));
}
_logNumClients(ws)
{
console.log('[websocket] numclients '+this._clients.length);
}
_removeClient(ws)
{
this._clients.splice(this._clients.indexOf(ws));
this._logNumClients();
}
send(msg)
{
var str=JSON.stringify(msg);
for(var i=0;i<this._clients.length;i++)
{
if (this._clients[i].readyState !== WebSocket.OPEN) {
console.log('[websocket] client '+i+' readystate ',this._clients[i].readyState);
continue;
}
this._clients[i].send(str);
}
}
}
const wsh=new WebsocketHandler();
wsh.start();