UNPKG

node-jet

Version:

Jet Realtime Message Bus for the Web. Daemon and Peer implementation.

61 lines (60 loc) 1.95 kB
/* istanbul ignore file */ import { EventEmitter, WebSocketImpl } from './index.js'; import { WebSocketServer as WsServer } from 'ws'; import { Socket } from './socket.js'; /** * Class implementation of a WS server. This implementation only runs in a node.js environment */ export class WebsocketServer extends EventEmitter { config; wsServer; connectionId = 1; constructor(config) { super(); this.config = config; } /** * method to start listening on incoming websocket connections. Incoming websocket connections are validated if they accept jet protocol */ listen() { this.wsServer = new WsServer({ port: this.config.wsPort, server: this.config.server, path: this.config.wsPath, handleProtocols: (protocols) => { if (protocols.has('jet')) { return 'jet'; } else { return false; } } }); this.wsServer.on('connection', (ws) => { const sock = new Socket(ws); sock.id = `ws_${this.connectionId}`; this.connectionId++; const pingMs = this.config.wsPingInterval || 5000; let pingInterval; if (pingMs) { pingInterval = setInterval(() => { if (ws.readyState === WebSocketImpl.OPEN) { ws.ping(); } }, pingMs); } ws.addListener('close', () => { clearInterval(pingInterval); this.emit('disconnect', sock); }); ws.addListener('disconnect', () => { this.emit('disconnect', sock); }); this.emit('connection', sock); }); } /** Method to stop Websocket server */ close() { this.wsServer.close(); } }