bfcache: server - Implement WebSocket server functionality
* Added WebSocketServer class with configurable options * Introduced WebSocketServerFactory for creating WebSocket relay servers * Updated index.ts to set up a server with WebSocket support and handle various signals for graceful shutdown
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import {LoggerFactory} from '@techniker-me/logger';
|
||||
import WebSocketServer, {WebSocketServerOptions} from './WebSocketServer';
|
||||
import {ServerWebSocket} from 'bun';
|
||||
|
||||
export default class WebSocketServerFactory {
|
||||
public static createWebSocketRelayServer(): WebSocketServer {
|
||||
const logger = LoggerFactory.getLogger('WebSocketRelayServer');
|
||||
const clients = new Set<ServerWebSocket>();
|
||||
const webSocketRelayServerOptions: WebSocketServerOptions = {
|
||||
onSocketError: (client, error) => logger.error(`Error: [%o] [${error.message}]`, client),
|
||||
onSocketOpen: client => {
|
||||
logger.debug('New WebSocketClient [%o]', client);
|
||||
|
||||
clients.add(client);
|
||||
},
|
||||
onSocketMessage: (fromClient, message) => {
|
||||
logger.debug(`Relaying message [%o]`, message);
|
||||
|
||||
for (const client of clients) {
|
||||
if (client === fromClient) {
|
||||
continue;
|
||||
}
|
||||
|
||||
client.send(message);
|
||||
}
|
||||
},
|
||||
onSocketClose: client => clients.delete(client),
|
||||
onSocketDrain: client => logger.debug('Client drain [%o]', client),
|
||||
publishToSelf: false
|
||||
};
|
||||
|
||||
return new WebSocketServer(webSocketRelayServerOptions);
|
||||
}
|
||||
private constructor() {
|
||||
throw new Error('WebSocketServerFactory is a static class that may not be instantiated');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user