Socket.io connect with server offline

2019-03-26 00:32发布

How do I detect if the server is offline, or for some other reason cannot connect. My code looks something like this.

this.socket = io.connect(connectionInfo, {
    reconnect:false
});

It does not throw any error, so a try/catch clause is not working.

3条回答
Summer. ? 凉城
2楼-- · 2019-03-26 00:56

If your server is offline and Client tries to connect use:

socket.on('error', function (err) {
    console.log(err);
});

So Client knows he can not reach the server.

查看更多
手持菜刀,她持情操
3楼-- · 2019-03-26 01:16

Since the 1.0 update, connection events are different. read this page for more info: http://socket.io/docs/migrating-from-0-9/

In my case, i could detect a connection error like so:

var manager = io.Manager('http://'+window.location.hostname+':3000', { /* options */ });
manager.socket('/namespace');
manager.on('connect_error', function() {
    console.log("Connection error!");
});

this.socket = io.connect('http://'+window.location.hostname+':3000');
查看更多
对你真心纯属浪费
4楼-- · 2019-03-26 01:18

Use

  • this.socket.on("connect") to catch connection events
  • this.socket.on("disconnect") to catch disconnection events
  • this.socket.on("connect_failed") to catch failed connection attempts

Use this.socket.io.on("connect_error", callback) to catch if the server is offline.

You can find all events, at https://github.com/LearnBoost/socket.io/wiki/Exposed-events

查看更多
登录 后发表回答