I use Socket.IO 0.9.16 to establish a connection:
io.connect(url)
However, when the server dies, it takes 2 minutes timeout to detect error with the server.
I already tried to reduce timeout to 5s by setting:
io.connect(url, {'timeout': 5000, 'connect_timeout': 5000})
But no success... How can I do this?
The challenge here is that there are a bunch of different settings that interact with each other and some retry logic that all make a socket.io timeout not what you would normally expect. I should add that I am familiar with socket.io 1.0+, not 0.9 though this probably applies to both.
Lets review how a socket.io connection works.
timeout
value that you pass in the initial options for a connection result.connect_error
and if you register for that message on the socket withsocket.on('connect_error', function() {...});
, you will see thatconnect_error
event.connect_error
is not a timeout. So, if the connection fails quickly (which it usually does when the server is just down), then you never get the regular timeout and the timeout argument you pass toio({timeout: 5000})
really doesn't come into effect. That only comes into effect when a connection to a server is just taking a long time (like an overly busy server or a server that accepted the TCP connection, but is really slow at responding). This is not usually what happens when a server is just down or unreachable.connect_error
it marks this socket.io connection for retry.reconnectionDelay
option is part of the formula, but in looking at the code, there is also a backoff algorithm that lengthens the time between retries the more times it has retried. So, suffice it to say, there's some algorithm that calculates a given delay before retrying that varies for each retry.reconnectionAttempts
that specifies the maximum number of reconnection attempts. This default to infinity if you don't pass it. But, if you pass10
, then it will give up after 10 successive connection failures.reconnectionAttempts
, then after that many unsuccessful connection attempts, you will get areconnect_failed
event on the socket and it will give up.timeout
option applies only to a single reconnect attempt and not to the total amount of time it keeps trying to connect.In a sample test page I've been experimenting with, I was able to implement my own traditional connection timeout like this:
This will wait a maximum of 5 seconds for a successful connection, regardless of how long a connection attempt takes or many reconnect attempts occur in that span of time. After 5 seconds without a successful connection, it shuts down the socket.
In my test app, I can see socket.io happily retrying the connection over and over again until after 5 seconds, my timer fires, I get notified of the
"timeout"
and I close the socket and it stops trying to retry any more.I think it is
connect timeout