socket.io - works first time, not second time onwards socket.io - works first time, not second time onwards express express

socket.io - works first time, not second time onwards


Socket.io 0.7 onwards will try and reuse connections to the same host. In my experience I've found this behaviour can be a little flakey.

I can't tell from the small code sample you provided, but I suspect the problem is that the second call to connect() is trying to reuse the first (closed) connection.

The workaround is to pass the 'force new connection' option when you call connect(). Eg:

io.connect("http://localhost", {'force new connection': true});


Your second line discards the object created in the first line. Simply doing this should work:

var socket = io.connect();

The problem with first send and second fail could be due to browser/protocol. I have seen such behaviour with Internet Explorer and XHR transport, and also with Opera using JSONP.

If you are using IE, try switching to JSONP and it should work properly. This can be done on the server side, by supplying the transport list to configuration. Just make sure JSONP comes before XHR. Something like this:

sio.set('transports', [    'websocket'    , 'flashsocket'    , 'jsonp-polling'    , 'xhr-polling'    , 'htmlfile']);


As of socket.io 1.0, two settings control this behaviour:

  • "force new connection":true, on the client connect() call.

  • "cookie":false, on the server Server() constructor.

Apparently, both produce the exact same behaviour.

The second method is, as of today, undocumented. However, looking at the source code you can see that all options passed to socket.io Server() are passed to the internal Engine.io library Server() constructor, which lets you change any of the options there. These options are documented here:

https://github.com/LearnBoost/engine.io