我正在尝试从我的socket.io-client(在Node.js上运行)到远程websocket的持久连接。我无法控制远程套接字,有时它可能会完全崩溃。每当发生错误或断开连接时,我都想尝试reconnect()。在下面的示例中,我尝试测试远程主机拒绝连接的情况。在这种情况下,我想尝试1秒后重新连接。它再次调用,然后退出。

这是代码:

var events = require('events'),
    util = require('util'),
    io = require('socket.io-client'),
    url = "ws://localhost:12345", // intentionally an unreachable URL
    socketOptions = {
        "transports" : [ "websocket" ],
        "try multiple transports" : false,
        "reconnect" : false,
        "connect timeout" : 5000
    };


// The goal is to have this socket attempt to connect forever
// I would like to do it without the built in reconnects, as these
// are somewhat unreliable (reconnect* events not always firing)

function Test(){
    var self = this;
    events.EventEmitter.call(self);

    var socket;

    function reconnect(){
        setTimeout(go, 1000);
    }

    function go(){

        console.log("connecting to", url, socketOptions);

        socket = io.connect(url, socketOptions);

        socket.on('connect', function(){
            console.log("connected! wat.");
        });

        socket.on('error', function(err){
            console.log("socket.io-client 'error'", err);
            reconnect();
        });

        socket.on('connect_failed', function(){
            console.log("socket.io-client 'connect_failed'");
            reconnect();
        });

        socket.on('disconnect', function(){
            console.log("socket.io-client 'disconnect'");
            reconnect();
        });
    }

    go();
}

util.inherits(Test, events.EventEmitter);


var test = new Test();


process.on('exit', function(){
    console.log("this should never end");
});


在节点0.11.0下运行它时,我得到以下信息:

$ node socketio_websocket.js
connecting to ws://localhost:12345 { transports: [ 'websocket' ],
  'try multiple transports': false,
  reconnect: false,
  'connect timeout': 5000 }
socket.io-client 'error' Error: connect ECONNREFUSED
    at errnoException (net.js:878:11)
    at Object.afterConnect [as oncomplete] (net.js:869:19)
connecting to ws://localhost:12345 { transports: [ 'websocket' ],
  'try multiple transports': false,
  reconnect: false,
  'connect timeout': 5000 }
this should never end

最佳答案

ECONNREFUSED是您无法管理的例外。
试试这个:

process.on('uncaughtException', function(err) {
    if(err.code == 'ECONNREFUSED'){
        reconnect();
    }
}


编辑

修改这样的选项:

socketOptions = {
    "transports" : [ "websocket" ],
    "try multiple transports" : false,
    "reconnect" : false,
    'force new connection': true, // <-- Add this!
    "connect timeout" : 5000
};


和重新连接功能(在注释中查看解释)

function reconnect(){
    socket.removeAllListeners();
    setTimeout(go, 1000);
}


可能socket.io重用了相同的连接而没有创建新的连接,从而迫使应用程序正常工作

关于node.js - socket.io客户端持久重试到无法访问的主机,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15802033/

10-12 12:34
查看更多