Commit | Line | Data |
---|---|---|
8244f5f0 JB |
1 | import { ProtocolCommand, ProtocolRequest, ProtocolVersion } from '../types/UIProtocol'; |
2 | ||
3 | import AbstractUIService from './WebSocketServices/ui/AbstractUIService'; | |
2a78593f | 4 | import { IncomingMessage } from 'http'; |
8244f5f0 JB |
5 | import UIService from './WebSocketServices/ui/0.0.1/UIService'; |
6 | import Utils from '../utils/Utils'; | |
2a78593f JB |
7 | import WebSocket from 'ws'; |
8 | import logger from '../utils/Logger'; | |
9 | ||
2a78593f | 10 | export default class WebSocketServer extends WebSocket.Server { |
8244f5f0 JB |
11 | private webSocketServerService: AbstractUIService; |
12 | ||
2a78593f JB |
13 | public constructor(options?: WebSocket.ServerOptions, callback?: () => void) { |
14 | // Create the WebSocket Server | |
15 | super(options, callback); | |
8244f5f0 JB |
16 | // FIXME: version the instantiation |
17 | this.webSocketServerService = new UIService(this); | |
2a78593f JB |
18 | } |
19 | ||
20 | public broadcastToClients(message: Record<string, unknown>): void { | |
21 | for (const client of this.clients) { | |
22 | if (client?.readyState === WebSocket.OPEN) { | |
23 | client.send(message); | |
24 | } | |
25 | } | |
26 | } | |
27 | ||
28 | public start(): void { | |
8244f5f0 | 29 | this.on('connection', (socket: WebSocket, request: IncomingMessage): void => { |
87002425 JB |
30 | // FIXME: Check connection validity |
31 | socket.on('message', (messageData) => { | |
32 | let [version, command, payload]: ProtocolRequest = [ProtocolVersion['0.0.1'], ProtocolCommand.UNKNOWN, {}]; | |
33 | // FIXME: check for iterable object | |
34 | [version, command, payload] = JSON.parse(messageData.toString()) as ProtocolRequest; | |
35 | switch (version) { | |
36 | case ProtocolVersion['0.0.1']: | |
37 | this.webSocketServerService.handleMessage(command, payload).catch(() => { | |
38 | logger.error(`${this.logPrefix()} Error while handling command %s message: %j`, command, payload); | |
39 | }); | |
40 | break; | |
41 | default: | |
42 | logger.error(`${this.logPrefix()} Unknown protocol version: ${version}`); | |
43 | } | |
44 | }); | |
45 | socket.on('error', (error) => { | |
46 | logger.error(`${this.logPrefix()} Error on WebSocket: %j`, error); | |
47 | }); | |
2a78593f JB |
48 | }); |
49 | } | |
8244f5f0 JB |
50 | |
51 | public stop(): void { | |
52 | this.close(); | |
53 | } | |
54 | ||
55 | public logPrefix(): string { | |
56 | return Utils.logPrefix('WebSocket Server:'); | |
57 | } | |
2a78593f | 58 | } |