Skip to content

Commit

Permalink
fix(server): respect sockPath on transportMode: 'ws' (#2310)
Browse files Browse the repository at this point in the history
  • Loading branch information
joonas-lahtinen committed Nov 9, 2019
1 parent a391b18 commit ee3e805
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
18 changes: 17 additions & 1 deletion lib/servers/WebsocketServer.js
Expand Up @@ -3,22 +3,38 @@
/* eslint-disable
class-methods-use-this
*/
const url = require('url');
const ws = require('ws');
const BaseServer = require('./BaseServer');

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.shouldUpgrade(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);
});
}

shouldUpgrade(req) {
const pathname = url.parse(req.url).pathname;
return pathname.match(`${this.server.sockPath}/?`);
}

send(connection, message) {
// prevent cases where the server is trying to send data while connection is closing
if (connection.readyState !== 1) {
Expand Down
46 changes: 46 additions & 0 deletions test/server/servers/WebsocketServer.test.js
Expand Up @@ -85,6 +85,52 @@ describe('WebsocketServer', () => {
done();
}, 3000);
});

it('should match sockPath', (done) => {
let receivedConnection = false;
socketServer.onConnection(() => {
receivedConnection = true;
});

// eslint-disable-next-line new-cap
const client = new ws(`http://localhost:${port}/ws-server`);

setTimeout(() => {
// the client closes itself, the server does not close it
client.close();
}, 1000);

setTimeout(() => {
expect(receivedConnection).toBeTruthy();
done();
}, 3000);
});

it('should ignore other paths', (done) => {
let receivedConnection = false;
socketServer.onConnection(() => {
receivedConnection = true;
});

// eslint-disable-next-line new-cap
const client = new ws(`http://localhost:${port}/ws-server-NOT`);

let receivedError = false;
client.on('error', () => {
receivedError = true;
});

setTimeout(() => {
// the client closes itself, the server does not close it
client.close();
}, 1000);

setTimeout(() => {
expect(receivedError).toBeTruthy();
expect(receivedConnection).toBeFalsy();
done();
}, 3000);
});
});

afterAll((done) => {
Expand Down

0 comments on commit ee3e805

Please sign in to comment.