等待/重新连接,直到可以建立TCP客户端连接?

时间:2019-01-25 14:01:35

标签: node.js

这里是一个如何从节点net docs(https://nodejs.org/api/net.html#net_net_connect_options_connectlistener)创建TCP客户端连接的示例

const client = net.createConnection({ port: 1905 }, () => {
    // 'connect' listener
    console.log('connected to server!');
    client.write('world!\r\n');
});
client.on('data', (data) => {
    console.log(data.toString());
    client.end();
});
client.on('end', () => {
    console.log('disconnected from server');
});

如果服务器不可用,则会显示Error: connect ECONNREFUSED 127.0.0.1:1905

等待/重新连接服务器直到可用时再进行连接而不是抛出错误的好方法是什么?

编辑:这是我尝试过的另一种方法,但是在这里我遇到了问题

  

MaxListenersExceededWarning:可能的EventEmitter内存泄漏   检测到。添加了11个连接侦听器。使用generator.setMaxListeners()来   增加限制

我希望最新的侦听器替换以前的侦听器。他们都听同一件事。我只想重试。

function initTcpClient() {
    console.log("Initiating TCP client...")
    var tcpSocket = new net.Socket();
    const client = net.createConnection({ port: 1905 }, () => {

    tcpSocket.on('error', function onError(err) {
        setTimeout(connect, 1000);
    });

    connect();

    function connect() {
        console.log("Looking for TCP server...");
        tcpSocket.connect(argv.tcpport, argv.tcphost, function onConnected() {
            console.log("Connecting to TCP server...");
            tcpSocket.on('data', function onIncoming(data) {
                if (connectedWebsocketClient) {
                    console.log('Forwarding to WebSocket: %s', data);
                    webSocketClient.send(data.toString());
                } else {
                    console.log('Not connected to websocket client. Dropping incoming TCP message: %s', data);
                }
            });
            tcpSocket.on('close', function onClose(hadError) {
                console.log("Connection to TCP server was closed.");
                connectedToTcpServer = false;
                setTimeout(connect, 1000);
            });
            console.log("Connected to TCP server.");
            connectedToTcpServer = true;
        });

    }

}

1 个答案:

答案 0 :(得分:1)

在此详细说明我的评论。是一个可行的例子。在简单的tcp服务器上尝试一下。启动客户端,然后在几秒钟后启动服务器。在onError中发生重新连接后,请务必为您注册侦听器,这一点很重要。您可能还希望限制尝试重新连接的次数。

const net = require('net')

let client = connect()
client.on('data', onData);
client.on('error', onError);
client.on("close", onClose);


function onData(data) {
    console.log(data)
}

function onError(err) {
    if(err.message.indexOf('ECONNREFUSED') > -1) {
        //do recconect
        console.log("Attempting to reconnect shortly")
        setTimeout(()=>{
            client = connect();
            client.on('data', onData);
            client.on('error', onError);
            client.on("close", onClose);

        },1000)
    }
}
 function onClose() {
    console.log("Removng all listeners")
    client.removeAllListeners("data");
    client.removeAllListeners("error")
}




function connect() {
    const c = net.createConnection({
        port: 3000
   },
    ()=>{
        console.log('connected')
    });

    return c
}