Socket.io脱机连接服务器

Socket.io connect with server offline

本文关键字:服务器 连接 脱机 io Socket      更新时间:2023-09-26

如何检测服务器是否脱机,或者由于其他原因无法连接。我的代码看起来像这样。

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

它没有抛出任何错误,因此try/catch子句不起作用。

使用

  • this.socket.on("connect", callback)捕获连接事件
  • this.socket.on("disconnect", callback)捕获断开连接事件
  • this.socket.on("connect_failed", callback)捕获失败的连接尝试
  • 如果服务器脱机,则捕获this.socket.io.on("connect_error", callback)

您可以在上找到所有活动https://github.com/LearnBoost/socket.io/wiki/Exposed-events

自1.0更新以来,连接事件有所不同。阅读本页了解更多信息:http://socket.io/docs/migrating-from-0-9/

在我的情况下,我可以检测到这样的连接错误:

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');

如果您的服务器离线,客户端尝试连接,请使用:

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

所以客户端知道他无法访问服务器。