Socket.io离线连接服务器
如何检测服务器是否脱机,或由于其他原因无法连接。 我的代码看起来像这样。
this.socket = io.connect(connectionInfo, { reconnect:false });
它不会抛出任何错误,所以try / catch子句不起作用。
使用
-
this.socket.on("connect")
捕获连接事件 -
this.socket.on("disconnect")
来捕捉断开事件 -
this.socket.on("connect_failed")
捕获失败的连接尝试
使用this.socket.io.on(“connect_error”,callback)来捕获服务器是否离线。
你可以find所有的事件,在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); });
所以客户知道他不能到达服务器。