nodejs NET api 错误?寻求完美的重新连接修复

nodejs NET api bug? Seeking flawless reconnect fix

我认为 Nodejs v5.3.0 NET api 可能存在问题。当套接字被销毁时,我想依赖 socket.remoteAddress 字段翻转到未定义。

这里的挑战是上面的可能语言(为强调而添加了粗体)。

上下文:我正在编写一个使用套接字与远程设备通信的 MEaN 应用程序。连接经常断开,我需要在使用前无缝重新连接。在他们想要传输以确保连接有效之前,我有传输调用 connect() 所需的各种功能。


根据 mscdex 修复更新:

if ( !client.readable )
    client.connect(PORT,HOST);
else
    logger.debug('Attempt to reconnect on an active connection. Ignored.');

client.readable 提供网络连接的即时状态,即使意图是写入连接。 client.writable 被缓冲,因此 'lies'(过于乐观)关于存在或能够建立的连接。


下面是工作代码:

var logger = require('winston');
var net = require('net');
var client = new net.Socket();

var init = function() {
    logger.info('Calling connect now...' );
    connect();
};
exports.init = init;

var output = function(action, id) {
    connect();
    //Transmit stuff  here
};
exports.output = output;

var connect = function() {
    // Check to see if remoteAddress is undefined. If so, then connect
    logger.debug('Test if connection is active: ' + client.remoteAddress);
    if ( typeof (client.remoteAddress) == 'undefined' ) {
        client.connect( 2101, '10.10.10.4', function() {
            logger.info('Connection now open');
        });
    }
    else {
        logger.debug('Attempting reconnect on active connection. Ignore: ' + client.remoteAddress);
    }
};

// This events, as expected, when the VPN is connected and data is received.
client.on('data', function() {
    logger.debug('Data incoming');
});

// This events, as expected, when the VPN drops
client.on('error', function() {
    logger.debug('Connection error so destroy() the client');
    client.destroy();
    // I *was* expecting destroy() to make typeof (client.remoteAddress) = 'undefined'. It does not.
});

结果日志如下所示

info: Calling connect now...
debug: Test if connection is active: undefined
info: Connection now open
debug: Data incoming
debug: Data incoming

debug: Test if connection is active: 10.10.10.4
debug: Attempting reconnect on active connection. Ignore: 10.10.10.4
POST /elk/output 200 18.122 ms - 2

debug: Data incoming

我断开了 VPN

debug: Test if connection is active: 10.10.10.4
debug: Attempting reconnect on active connection. Ignore: 10.10.10.4
POST /elk/output 200 1.546 ms - 2
debug: Connection error so destroy() the client

现在,给定 client.destroy();调用,我希望 client.remoteAddress 每个文档都未定义,但事实并非如此。

debug: Test if connection is active: 10.10.10.4
debug: Attempting reconnect on active connection. Ignore: 10.10.10.4
debug: Connection error so destroy() the client
POST /elk/output 200 1.063 ms - 2

想法?

谢谢

不使用remote ip检测远程连接是否断开。相反,也订阅 close event (and depending on the use case, maybe the end 事件):

client.on('close',function(){
    // client has been disconnected.
    connect();
});

client.on('end',function(){
    // client wants to disconnect.
    connect();
});

要真正关闭套接字,您可以将 close(和 end)处理程序设置为不执行任何操作:

client.on('close',function(){});
client.destroy();

您还可以通过检查 client.readable.

来检查 TCP 流是否可读