-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWSService.ts
63 lines (53 loc) · 1.59 KB
/
WSService.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
import WebSocket, { MessageEvent } from 'ws';
import { SimpleService } from './server';
type WSServiceMessageCallback = (instance: WSService, event: MessageEvent) => void;
/**
* WSService
* a simple WebSocker server
*/
class WSService extends SimpleService {
sockets: WebSocket[];
server: WebSocket.Server;
port: number;
binaryType: string;
onMessageCallback: WSServiceMessageCallback;
constructor(name: string = 'WSService', port: number = 8080, binaryType: string = 'blob', onMessage: WSServiceMessageCallback) {
super(name);
this.port = port;
this.binaryType = binaryType;// Note BinaryType of Receiver and Sender must be the same
this.sockets = [];
this.onMessageCallback = onMessage ? onMessage : () => null;
this.server = new WebSocket.Server({
port
});
}
/**
* start the wesocket service
* implement callbacks for events
*/
start() {
this.server.on('connection', (socket) => {
socket.binaryType = this.binaryType;
this.sockets.push(socket);
socket.onmessage = (event) => this.onMessageCallback(this, event);
// When a socket closes, or disconnects, remove it from the array.
socket.on('close', () => {
this.sockets = this.sockets.filter(s => s !== socket);
});
});
console.log(this.name, this.port);
return true;
}
/**
* Send Data to all currently conected WS Clients
* @param data data to be sent
*/
broadcast(data: WebSocket.Data) {
this.sockets.forEach(s => s.send(data));
}
stop() {
this.server.close();
return true;
}
}
export default WSService;