When using noServer: true, you must manually call server.handleUpgrade() to upgrade an HTTP request to a WebSocket connection.
Method Signature:
server.handleUpgrade(request, socket, head, callback)
request {http.IncomingMessage}: The client HTTP GET request.socket {stream.Duplex}: The network socket.head {Buffer}: The first packet of the upgraded stream.callback {Function}: Called with (websocket, request) upon success.
Example:
const { WebSocketServer } = require('ws');
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(404);
res.end();
});
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', (req, socket, head) => {
if (wss.shouldHandle(req)) {
wss.handleUpgrade(req, socket, head, (ws) => {
ws.on('message', (msg) => console.log('Received:', msg));
});
} else {
socket.destroy();
}
});
server.listen(8080);
server.handleUpgrade(request, socket, head, (websocket, request) => {
// websocket is the new WebSocket instance
// request is the original http.IncomingMessage
});