diff --git a/lib/servers/WebsocketServer.js b/lib/servers/WebsocketServer.js index 21bfb0c344..8424b6d382 100644 --- a/lib/servers/WebsocketServer.js +++ b/lib/servers/WebsocketServer.js @@ -10,10 +10,20 @@ module.exports = class WebsocketServer extends BaseServer { constructor(server) { super(server); this.wsServer = new ws.Server({ - server: this.server.listeningApp, + noServer: true, path: this.server.sockPath, }); + this.server.listeningApp.on('upgrade', (req, sock, head) => { + if (!this.wsServer.shouldHandle(req)) { + return; + } + + this.wsServer.handleUpgrade(req, sock, head, (connection) => { + this.wsServer.emit('connection', connection, req); + }); + }); + this.wsServer.on('error', (err) => { this.server.log.error(err.message); }); diff --git a/test/server/servers/WebsocketServer.test.js b/test/server/servers/WebsocketServer.test.js index e8e59a786b..23dd8c9564 100644 --- a/test/server/servers/WebsocketServer.test.js +++ b/test/server/servers/WebsocketServer.test.js @@ -85,6 +85,60 @@ describe('WebsocketServer', () => { done(); }, 3000); }); + + it('should match sockPath', (done) => { + let receivedConnection = false; + socketServer.onConnection((connection) => { + receivedConnection = true; + connection.close(4000); + }); + + // eslint-disable-next-line new-cap + const client = new ws(`http://localhost:${port}/ws-server?YEP`); + + let receivedError = false; + client.onerror = (e) => { + receivedError = e.error; + }; + + client.onclose = (e) => { + expect(e.code).toEqual(4000); + }; + + setTimeout(() => { + expect(receivedConnection).toBeTruthy(); + expect(receivedError).toBeFalsy(); + done(); + }, 3000); + }); + + it('should ignore other paths', (done) => { + let receivedConnection = false; + socketServer.onConnection((connection) => { + receivedConnection = true; + connection.close(4000); + }); + + // eslint-disable-next-line new-cap + const client = new ws(`http://localhost:${port}/ws-server-NOT`, { + handshakeTimeout: 1000, + }); + + let receivedError = false; + client.onerror = (e) => { + receivedError = e.error; + }; + + client.onclose = (e) => { + expect(e.code).not.toEqual(4000); + }; + + setTimeout(() => { + expect(receivedConnection).toBeFalsy(); + expect(receivedError).toBeTruthy(); + done(); + }, 3000); + }); }); afterAll((done) => {