简体   繁体   中英

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?

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 .

Ok solution is simple (unfortunately half day of debugging and now it's simple :)).

There is an option 'destroy upgrade' for upgrade requests coming from non-socketio clients. Since Websocket (module 'ws') is using the same requests some of them might be for 'ws' not for 'socket.io'. So this option should be disabled.

io = require('socket.io').listen(server,  { log: false, 'resource':'/socket.io'  });
io.disable('destroy upgrade') 

Update for 2016:

io.disable('destroy upgrade');

seems not to be available anymore. But I succeeded by assigning the websocket module ws a path (using Express):

 var wss = new WebSocketServer({ server: server, path: '/ws' }); //do not interfere with socket.io

Of course the client has the same path ws://theserver.com/ws

I did not have to alter the socket.io side at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM