-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWaitHandleServer.ts
94 lines (71 loc) · 2.42 KB
/
WaitHandleServer.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { createServer } from 'http';
import { type AddressInfo, type WebSocket, WebSocketServer } from 'ws';
interface WaitHandleIncomingMessage {
action: 'wait' | 'release';
id: string;
}
interface WaitHandleOutgoingMessage {
action: 'released';
id: string;
}
export class WaitHandleServer {
public readonly port: number;
private socketServer: WebSocketServer;
private connections: Map<number, WebSocket>;
private subscribedSockets: Map<string, number[]>;
private webSocketIdValue: number = 0;
constructor() {
this.connections = new Map();
this.subscribedSockets = new Map();
const httpServer = createServer();
this.socketServer = new WebSocketServer({ server: httpServer });
const generateWebSocketId = () => {
this.webSocketIdValue += 1;
return this.webSocketIdValue;
};
this.socketServer.on('connection', (ws) => {
const socketId = generateWebSocketId();
ws.on('message', (data: Buffer | Buffer[]) => {
const incomingMessage = JSON.parse(
data.toString()
) as WaitHandleIncomingMessage;
const { id } = incomingMessage;
if (incomingMessage.action === 'wait') {
if (this.subscribedSockets.has(id)) {
this.subscribedSockets.get(id)!.push(socketId);
} else {
this.subscribedSockets.set(id, [socketId]);
}
}
if (incomingMessage.action === 'release') {
if (!this.subscribedSockets.has(id)) {
return;
}
const subscribedSocketIds = this.subscribedSockets.get(id)!;
for (const subscribedSocketId of subscribedSocketIds) {
if (!this.connections.has(subscribedSocketId)) {
// eslint-disable-next-line no-continue
continue;
}
const socket = this.connections.get(socketId)!;
const outgoingMessage = {
action: 'released',
id,
} as WaitHandleOutgoingMessage;
socket.send(JSON.stringify(outgoingMessage));
}
// we clear the wait collection
this.subscribedSockets.delete(id);
}
});
this.connections.set(socketId, ws);
ws.on('close', () => {
this.connections.delete(socketId);
});
});
httpServer.listen();
// we assume its TCP
const address = httpServer.address() as AddressInfo;
this.port = address.port;
}
}