1 import { Protocol
, ProtocolVersion
} from
'../../types/UIProtocol';
3 import { AbstractUIServer
} from
'./AbstractUIServer';
4 import Configuration from
'../../utils/Configuration';
5 import { IncomingMessage
} from
'http';
6 import { ServerOptions
} from
'../../types/ConfigurationData';
7 import UIServiceFactory from
'./ui-services/UIServiceFactory';
8 import Utils from
'../../utils/Utils';
9 import WebSocket from
'ws';
10 import logger from
'../../utils/Logger';
12 export default class UIWebSocketServer
extends AbstractUIServer
{
13 public constructor(options
?: ServerOptions
) {
15 this.server
= new WebSocket
.Server(options
?? Configuration
.getUIServer().options
);
18 public start(): void {
19 this.server
.on('connection', (socket
: WebSocket
, request
: IncomingMessage
): void => {
20 const protocolIndex
= socket
.protocol
.indexOf(Protocol
.UI
);
21 const version
= socket
.protocol
.substring(
22 protocolIndex
+ Protocol
.UI
.length
24 if (!this.uiServices
.has(version
)) {
25 this.uiServices
.set(version
, UIServiceFactory
.getUIServiceImplementation(version
, this));
27 // FIXME: check connection validity
28 socket
.on('message', (messageData
) => {
31 .messageHandler(messageData
)
33 logger
.error(`${this.logPrefix()} Error while handling message data: %j`, messageData
);
36 socket
.on('error', (error
) => {
37 logger
.error(`${this.logPrefix()} Error on WebSocket: %j`, error
);
46 public sendResponse(message
: string): void {
47 this.broadcastToClients(message
);
50 public logPrefix(): string {
51 return Utils
.logPrefix(' UI WebSocket Server:');
54 private broadcastToClients(message
: string): void {
55 for (const client
of (this.server
as WebSocket
.Server
).clients
) {
56 if (client
?.readyState
=== WebSocket
.OPEN
) {