Joe
Joe

Reputation: 519

Handle connection error events

How do I catch when my socket.io client cannot connect to the provided server?

This does not seem to work:

var socket = io('http://example.com:3000');

socket.on('connect_fail', function() {
    console.log("fail"); // doesn't get here
});

If my server is offline the event won't fire, and in the console it will repeat: XMLHttpRequest cannot load http://example.com:3000/socket.io/?EIO=2&transport=polling&t=1407852011369-40. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://dashboard.inkstand.org' is therefore not allowed access.

Everything works as expected when the server is online.

I can't find any good documentation on this, or any for client connection events.

Upvotes: 0

Views: 175

Answers (2)

Joe
Joe

Reputation: 519

After more research I've found this is handled differently in v1.0.

var manager = io.Manager('http://example.com:3000', {});
var socket  = manager.socket('/');

manager.on('connect_error', function() {
    console.log("fail"); // does get here now
});

Upvotes: 0

Blubberguy22
Blubberguy22

Reputation: 1332

Instead of doing:

socket.on('connect_fail', function() {
    console.log("fail"); // doesn't get here
});

Try:

socket.on('error', function(err){
    console.log("fail");
    // Do stuff
});

This is fired when a connection fails (http://socket.io/docs/client-api/)

Upvotes: 1

Related Questions