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