Skip to content

Commit ee3e805

Browse files
fix(server): respect sockPath on transportMode: 'ws' (webpack#2310)
1 parent a391b18 commit ee3e805

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

lib/servers/WebsocketServer.js

+17-1
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,38 @@
33
/* eslint-disable
44
class-methods-use-this
55
*/
6+
const url = require('url');
67
const ws = require('ws');
78
const BaseServer = require('./BaseServer');
89

910
module.exports = class WebsocketServer extends BaseServer {
1011
constructor(server) {
1112
super(server);
1213
this.wsServer = new ws.Server({
13-
server: this.server.listeningApp,
14+
noServer: true,
1415
path: this.server.sockPath,
1516
});
1617

18+
this.server.listeningApp.on('upgrade', (req, sock, head) => {
19+
if (!this.shouldUpgrade(req)) {
20+
return;
21+
}
22+
23+
this.wsServer.handleUpgrade(req, sock, head, (connection) => {
24+
this.wsServer.emit('connection', connection, req);
25+
});
26+
});
27+
1728
this.wsServer.on('error', (err) => {
1829
this.server.log.error(err.message);
1930
});
2031
}
2132

33+
shouldUpgrade(req) {
34+
const pathname = url.parse(req.url).pathname;
35+
return pathname.match(`${this.server.sockPath}/?`);
36+
}
37+
2238
send(connection, message) {
2339
// prevent cases where the server is trying to send data while connection is closing
2440
if (connection.readyState !== 1) {

test/server/servers/WebsocketServer.test.js

+46
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,52 @@ describe('WebsocketServer', () => {
8585
done();
8686
}, 3000);
8787
});
88+
89+
it('should match sockPath', (done) => {
90+
let receivedConnection = false;
91+
socketServer.onConnection(() => {
92+
receivedConnection = true;
93+
});
94+
95+
// eslint-disable-next-line new-cap
96+
const client = new ws(`http://localhost:${port}/ws-server`);
97+
98+
setTimeout(() => {
99+
// the client closes itself, the server does not close it
100+
client.close();
101+
}, 1000);
102+
103+
setTimeout(() => {
104+
expect(receivedConnection).toBeTruthy();
105+
done();
106+
}, 3000);
107+
});
108+
109+
it('should ignore other paths', (done) => {
110+
let receivedConnection = false;
111+
socketServer.onConnection(() => {
112+
receivedConnection = true;
113+
});
114+
115+
// eslint-disable-next-line new-cap
116+
const client = new ws(`http://localhost:${port}/ws-server-NOT`);
117+
118+
let receivedError = false;
119+
client.on('error', () => {
120+
receivedError = true;
121+
});
122+
123+
setTimeout(() => {
124+
// the client closes itself, the server does not close it
125+
client.close();
126+
}, 1000);
127+
128+
setTimeout(() => {
129+
expect(receivedError).toBeTruthy();
130+
expect(receivedConnection).toBeFalsy();
131+
done();
132+
}, 3000);
133+
});
88134
});
89135

90136
afterAll((done) => {

0 commit comments

Comments
 (0)