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