Reputation: 908
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?
Upvotes: 4
Views: 2004
Reputation: 2402
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.
Upvotes: 0
Reputation: 17505
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
.
Upvotes: 1
Reputation: 908
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')
Upvotes: 0