Commit | Line | Data |
---|---|---|
4198ad5c | 1 | import { IncomingMessage } from 'http'; |
8114d10e | 2 | |
0d8140bd | 3 | import WebSocket from 'ws'; |
8114d10e JB |
4 | |
5 | import { ServerOptions } from '../../types/ConfigurationData'; | |
6 | import { Protocol, ProtocolVersion } from '../../types/UIProtocol'; | |
7 | import Configuration from '../../utils/Configuration'; | |
675fa8e3 | 8 | import logger from '../../utils/Logger'; |
8114d10e JB |
9 | import Utils from '../../utils/Utils'; |
10 | import { AbstractUIServer } from './AbstractUIServer'; | |
11 | import UIServiceFactory from './ui-services/UIServiceFactory'; | |
4198ad5c | 12 | |
fe94fce0 | 13 | export default class UIWebSocketServer extends AbstractUIServer { |
b153c0fd | 14 | public constructor(options?: ServerOptions) { |
fe94fce0 | 15 | super(); |
0d8140bd | 16 | this.server = new WebSocket.Server(options ?? Configuration.getUIServer().options); |
4198ad5c JB |
17 | } |
18 | ||
19 | public start(): void { | |
d200b695 | 20 | this.server.on('connection', (socket: WebSocket, request: IncomingMessage): void => { |
4198ad5c | 21 | const protocolIndex = socket.protocol.indexOf(Protocol.UI); |
e7aeea18 JB |
22 | const version = socket.protocol.substring( |
23 | protocolIndex + Protocol.UI.length | |
24 | ) as ProtocolVersion; | |
de9136ae | 25 | if (!this.uiServices.has(version)) { |
178ac666 | 26 | this.uiServices.set(version, UIServiceFactory.getUIServiceImplementation(version, this)); |
4198ad5c JB |
27 | } |
28 | // FIXME: check connection validity | |
29 | socket.on('message', (messageData) => { | |
e7aeea18 JB |
30 | this.uiServices |
31 | .get(version) | |
178ac666 | 32 | .messageHandler(messageData) |
e7aeea18 | 33 | .catch(() => { |
178ac666 | 34 | logger.error(`${this.logPrefix()} Error while handling message data: %j`, messageData); |
e7aeea18 | 35 | }); |
4198ad5c JB |
36 | }); |
37 | socket.on('error', (error) => { | |
9f2e3130 | 38 | logger.error(`${this.logPrefix()} Error on WebSocket: %j`, error); |
4198ad5c JB |
39 | }); |
40 | }); | |
41 | } | |
42 | ||
43 | public stop(): void { | |
d200b695 | 44 | this.server.close(); |
4198ad5c JB |
45 | } |
46 | ||
178ac666 JB |
47 | public sendResponse(message: string): void { |
48 | this.broadcastToClients(message); | |
49 | } | |
50 | ||
4198ad5c | 51 | public logPrefix(): string { |
410a760d | 52 | return Utils.logPrefix(' UI WebSocket Server:'); |
4198ad5c | 53 | } |
178ac666 JB |
54 | |
55 | private broadcastToClients(message: string): void { | |
0d8140bd JB |
56 | for (const client of (this.server as WebSocket.Server).clients) { |
57 | if (client?.readyState === WebSocket.OPEN) { | |
178ac666 JB |
58 | client.send(message); |
59 | } | |
60 | } | |
61 | } | |
4198ad5c | 62 | } |