Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io and Webscocket listen on the same server

I need to share same http server between socket.io and websocket (from 'ws' package) handlers. Unfortunatelly, despite that they are listening to diffrent prefixes, the first is listening to /socket.io and the second to /websocket urls, for some reasons if they are running on the same server the websocket is not working properly.

I did some debugging, but it seems that the requests are properly handled by both libraries but in the end only socket.io works properly.

Any idea how to solve that?

like image 317
Luman75 Avatar asked Apr 08 '26 13:04

Luman75


1 Answers

The way sockets work in node.js is quite a bit different from the way normal requests work. There is no routing, so rather than listening to a url, you have to listen to all sockets. The default behavior of socket.io is to close any socket connections that it doesn't recognize. To fix this, you'll need to add the flag 'destroy upgrade': false to the options (server is an express server):

require('socket.io').listen(server, {'destroy upgrade': false, ...})

You'll also need to check the url when a client connects (in the code handling /websocket) and ignore it if it looks like it belongs to socket.io. You can find the url from the client object (passed in to the on connection handler) as client.upgradeReq.url.

like image 133
Aaron Dufour Avatar answered Apr 10 '26 02:04

Aaron Dufour