ZombieBZ
Denoβ€’12mo agoβ€’
1 reply
ZombieB

Socket failing to transmit/receive when using 'upgrade' event and socket.write on Expressjs server

Hi, I'm using the
ws
npm module with my Express server (lots of routes were imported from a different project, one using Node with express in mind). Use of either
socket.end
or
socket.write
hangs the request.

The event listener is attached to the
Server
given by
app.listen()
.

The script with this bug commented out is here (ctrl+f for 'upgrade'): https://gitea.proxnet.dev/zombieb/galvanic-corrosion/src/branch/master/src/main.ts

I can reproduce the problem here:
import { WebSocketServer } from "ws";
import express from "express";

const app = express();

app.use((rq, rs) => {
    rs.sendStatus(404);
});

const wss = new WebSocketServer({ noServer: true, path: "/" });
wss.on('connection', socket => {
    socket.send("Hello World!");
    socket.on('message', data => {
        console.log(`Got data: ${data.toString()}`);
        
        if (data.toString() === "close") {
            socket.send("Bye!");
            socket.close();
        }
    });
});

const server = app.listen(3000);

server.on('upgrade', (req, socket, head) => {

    console.log('upgrade request');
    socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
    socket.end();
    wss.handleUpgrade(req, socket, head, ws => {
        wss.emit('connection', ws, req);
    });
});


Without
socket.write
and
socket.end
, the server works as expected. With them, the response hangs.
Is this something I should create an issue for?

Any help appreciated.
Was this page helpful?