-
Notifications
You must be signed in to change notification settings - Fork 383
/
wsprocessor.ts
66 lines (57 loc) · 1.44 KB
/
wsprocessor.ts
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
import { Server as HttpServer } from 'http';
import { EventEmitter } from 'events';
import * as util from 'util';
import * as net from 'net';
import * as WebSocket from 'ws';
let ST_STARTED = 1;
let ST_CLOSED = 2;
/**
* websocket protocol processor
*/
export class WSProcessor extends EventEmitter
{
httpServer: HttpServer;
wsServer: WebSocket.Server;
state: number;
constructor()
{
super();
this.httpServer = new HttpServer();
let self = this;
this.wsServer = new WebSocket.Server({ server: this.httpServer });
this.wsServer.on('connection', function (socket)
{
// emit socket to outside
self.emit('connection', socket);
});
this.state = ST_STARTED;
};
add(socket : net.Socket, data : Buffer)
{
if (this.state !== ST_STARTED)
{
return;
}
this.httpServer.emit('connection', socket);
if (typeof (socket as any).ondata === 'function')
{
// compatible with stream2
(socket as any).ondata(data, 0, data.length);
} else
{
// compatible with old stream
socket.emit('data', data);
}
};
close()
{
if (this.state !== ST_STARTED)
{
return;
}
this.state = ST_CLOSED;
this.wsServer.close();
this.wsServer = null;
this.httpServer = null;
};
}