HenningM / express-ws

WebSocket endpoints for express applications
BSD 2-Clause "Simplified" License
878 stars 142 forks source link

Dropping first message #113

Open michaeldfallen opened 5 years ago

michaeldfallen commented 5 years ago

I'm looking in to a noticeable delay that express-ws seems to be introducing into the websocket handling. The result of this delay is that if a client sends a message on open it won't be handled by the server.

I'm seeing a 90ms delay from the connection opening (from index.js L45 wsServer.on('connection', (socket, request) => {) to my app.ws('/socket', () => { ... }) handler being fired.

By adding a process.hrtime call at index.js line 45 I've measured between 96ms and 87ms delay.

Presumably this is due to the middleware between the websocket connecting and the handler firing but it seems odd to me that the websocket would respond with an open event until the websocket was really ready to receive requests.

As a work around I have as the last line in my handler a ws.send('ready') which clients must wait for before they can send their first message.

LukeNotable commented 4 years ago

In case any one else find this: Looks like on the connection event, all the middleware is then called before reaching the route handler, where I would naturally try to attach the message event handler. If the middleware awaits any promises, by then it's too late, as messages will have already arrived and been dropped. Short of making all my middleware synchronous, I don't see a fix without significant re-architecting.

darrinholst commented 2 years ago

Thanks for the workaround @michaeldfallen. Unfortunate that we need it, but at least it still works 3 years later.