gpt4 book ai didi

node.js - socket.io 客户端持续重试无法访问的主机

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:36 26 4
gpt4 key购买 nike

我正在尝试从我的 socket.io-client(在 Node.js 上运行)到远程 Websocket 建立持久连接。我无法控制远程套接字,有时它可能会完全崩溃。每当发生错误或断开连接时,我想尝试重新连接()。在下面的示例中,我尝试测试远程主机拒绝连接的情况。在这种情况下,我想在 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");
});

在 Node 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com