javascript Socket.io 离线连接服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18248128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Socket.io connect with server offline
提问by Adam
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.
它不会抛出任何错误,因此 try/catch 子句不起作用。
回答by Kurt Pattyn
Use
利用
this.socket.on("connect", callback)
to catch connection eventsthis.socket.on("disconnect", callback)
to catch disconnection eventsthis.socket.on("connect_failed", callback)
to catch failed connection attemptsthis.socket.io.on("connect_error", callback)
to catch if the server is offline
this.socket.on("connect", callback)
捕捉连接事件this.socket.on("disconnect", callback)
捕捉断线事件this.socket.on("connect_failed", callback)
捕获失败的连接尝试this.socket.io.on("connect_error", callback)
捕捉服务器是否离线
You can find all events, at https://github.com/LearnBoost/socket.io/wiki/Exposed-events
您可以在https://github.com/LearnBoost/socket.io/wiki/Exposed-events找到所有事件
回答by onok
Since the 1.0 update, connection events are different. read this page for more info: http://socket.io/docs/migrating-from-0-9/
自 1.0 更新以来,连接事件有所不同。阅读此页面了解更多信息: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');
回答by Zombi
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.
所以客户端知道他无法访问服务器。