I have a setup similar to this one:
var WebSocketServer = require(\"ws\").Server,
express = require(\"express\"),
http = require(\"http\"),
app =
UPDATE Paths are valid in the ws server options.
interface ServerOptions {
host?: string;
port?: number;
backlog?: number;
server?: http.Server | https.Server;
verifyClient?: VerifyClientCallbackAsync | VerifyClientCallbackSync;
handleProtocols?: any;
path?: string;
noServer?: boolean;
clientTracking?: boolean;
perMessageDeflate?: boolean | PerMessageDeflateOptions;
maxPayload?: number;
}
The accepted answer is no longer valid and will throw Frame Header Invalid errors. Pull Request #885.
WS Paths were removed as Lpinca puts it:
The problem here is that each WebSocketServer adds a new listener for the upgrade event on the HTTP server and when that event is emitted, handleUpgrade is called on all servers.
Here is the work around:
const wss1 = new WebSocket.Server({ noServer: true });
const wss2 = new WebSocket.Server({ noServer: true });
const server = http.createServer();
server.on('upgrade', (request, socket, head) => {
const pathname = url.parse(request.url).pathname;
if (pathname === '/foo') {
wss1.handleUpgrade(request, socket, head, (ws) => {
wss1.emit('connection', ws);
});
} else if (pathname === '/bar') {
wss2.handleUpgrade(request, socket, head, (ws) => {
wss2.emit('connection', ws);
});
} else {
socket.destroy();
}
});