Node.js socket.io-client connect_failed / connect_error 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8588689/
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
Node.js socket.io-client connect_failed / connect_error event
提问by Tk421
I am playing around with node.js and socket.io-client. I am trying to connect to a channel that does not exist in order to trigger the event 'connect_failed' (as specified at https://github.com/LearnBoost/socket.io-client).
我在玩 node.js 和 socket.io-client。我正在尝试连接到不存在的通道以触发事件“connect_failed”(如https://github.com/LearnBoost/socket.io-client所指定)。
However I can't get the event working:
但是我无法让事件正常工作:
var clientio = require('socket.io-client');
console.log('Trying stuff ...');
// the channel does not exist
var socket = clientio.connect( 'http://localhost:4000/news' );
// I expect this event to be triggered
socket.on('connect_error', function(){
console.log('Connection Failed');
});
socket.on('connect', function(){
console.log('Connected');
});
socket.on('disconnect', function () {
console.log('Disconnected');
});
socket.send('hi there');
If I execute will this will happen:
如果我执行会发生这种情况:
$ node tmp_clientio.js
Trying stuff ...
Any ideas about how to trigger an error if connecting to a channel that does not exist?
关于如何在连接到不存在的通道时触发错误的任何想法?
UPDATE: Renamed connect_failedto connect_error
更新:重命名connect_failed为connect_error
采纳答案by Tom Leys
I ran into the same issue. There is a un-documented difference between namespace mode on and off that I also ran into, in the end I had to use the chrome debugger to work it out.
我遇到了同样的问题。我还遇到了打开和关闭命名空间模式之间的未记录差异,最后我不得不使用 chrome 调试器来解决它。
// Bind to the news namespace, also get the underlying socket
var ns_news = clientio.connect( 'http://localhost:4000/news' );
var socket = ns_news.socket
So, you see above that you have to get the actual socketns_news.socketfrom your namespace if you want to bind "socket level" events such as connect failed, disconnect, etc
因此,您在上面看到,如果要绑定“套接字级别”事件(例如连接失败、断开连接等),则必须从命名空间中获取实际套接字ns_news.socket
// Global events are bound against socket
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
socket.on('connect', function(){
console.log('Connected');
});
socket.on('disconnect', function () {
console.log('Disconnected');
});
// Your events are bound against your namespace(s)
ns_news.on('myevent', function() {
// Custom event code here
});
Note that you now use ns_news to send or receive events
请注意,您现在使用 ns_news 来发送或接收事件
ns_news.send('hi there');
Finally, be sure to bind the socket.on('error', ...)event as well - it occurs if the port wasn't available
最后,一定要绑定socket.on('error', ...)事件——如果端口不可用,它就会发生
Full implimentation of 8080 connect with fallback to port 80
8080 连接的完整实现并回退到端口 80
I did this in my implementation (try port 8080, if that fails, try port 80 through nginx)
我在我的实现中这样做了(尝试端口 8080,如果失败,通过 nginx 尝试端口 80)
socket_port = 8080;
ns_dash = io.connect("http://your.gridspy.co.nz/dash", {
port: socket_port,
'connect timeout': 5000,
'flash policy port': 10843
});
socket = ns_dash.socket;
try_other_port = function() {
if (socket_port !== 80) {
if (typeof console !== "undefined" && console !== null) {
console.log("Trying other port, instead of port " + socket_port + ", attempting port 80");
}
socket_port = 80;
socket.options.port = socket_port;
socket.options.transports = ['htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'];
return socket.connect();
} else {
return typeof console !== "undefined" && console !== null ? console.log("No other ports to try.") : void 0;
}
};
socket.on('connect_failed', function() {
if (typeof console !== "undefined" && console !== null) {
console.log("Connect failed (port " + socket_port + ")");
}
return try_other_port();
});
socket.on('error', function() {
if (typeof console !== "undefined" && console !== null) {
console.log("Socket.io reported a generic error");
}
return try_other_port();
});
I also added an nginx proxy_pass rule, which looks like this
我还添加了一个 nginx proxy_pass 规则,看起来像这样
location ~ ^/(socket.io)/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
The Upgrade and Connection options here (from more recent versions of nginx) are required to upgrade the connection between nginx and socket.io to support websockets. That means that your webserver can support websockets on port 80.
这里的升级和连接选项(来自较新版本的 nginx)需要升级 nginx 和 socket.io 之间的连接以支持 websockets。这意味着您的网络服务器可以在端口 80 上支持 websockets。
Furthermore if your server supports ssl / https, this will proxy wss which is the secure version of websockets.
此外,如果您的服务器支持 ssl / https,这将代理 wss,这是 websockets 的安全版本。
回答by Soyoes
they changed the event name. use
他们更改了事件名称。用
reconnect_error
or
或者
connect_error
instead
反而
https://github.com/socketio/socket.io-client/blob/master/lib/socket.js#L27
https://github.com/socketio/socket.io-client/blob/master/lib/socket.js#L27
回答by alessioalex
From the documentation:
从文档:
connect_failed
Fired when the connection timeout occurs after the last connection attempt. This only fires if the connectTimeout option is set. If the tryTransportsOnConnectTimeout option is set, this only fires once all possible transports have been tried.
连接失败
在最后一次连接尝试后发生连接超时时触发。仅当设置了 connectTimeout 选项时才会触发。如果设置了 tryTransportsOnConnectTimeout 选项,则仅在尝试了所有可能的传输后才会触发。
So this event fires only if the connectTimeout option is set(the implementation for that is here: https://github.com/LearnBoost/socket.io-client/blob/master/lib/socket.js#L223-245).
因此,仅当设置了 connectTimeout 选项时才会触发此事件(其实现在这里:https: //github.com/LearnBoost/socket.io-client/blob/master/lib/socket.js#L223-245)。
So what you should do different in your code is:
所以你应该在你的代码中做不同的是:
io.connect('http://localhost:4000/news', { 'connect timeout': 5000 });
// set connect timeout to 5 seconds
回答by Eugene
This applies to version 1.4.5 (might work on previous versions also).
这适用于 1.4.5 版(也可能适用于以前的版本)。
What you want to do is listen for the "error" event on the socket.io client. It will trigger this event, and the error message will be "Invalid namespace".
您要做的是侦听 socket.io 客户端上的“错误”事件。它将触发此事件,错误消息将是“无效的命名空间”。
Here's an example of how to handle it from the socket.io client:
以下是如何从 socket.io 客户端处理它的示例:
var ioclient = require('socket.io-client');
var websocket = ioclient('http://myserverurl.com/namespacethatdoesntexist');
websocket.on('error', function(err){
if (err == 'Invalid namespace') {
console.warn("Attempted to connect to invalid namespace");
//handle the case here...
} else {
console.warn("Error on socket.io client", err);
}
});

