重试后客户端连接未正确关闭

Client connections not closed properly over retries

我有一个小型测试 telnet 客户端,需要对 android 设备执行身份验证。它工作正常,但是想了解该方法是否正确并且不会导致内存泄漏。

我认为此脚本可能导致内存泄漏的原因是,当连接建立时,我看到多个连接确认:

 node test.js
Connection refused, device not up yet..
Retrying..
Connection closed
CONNECTED TO: 127.0.0.1:5554
CONNECTED TO: 127.0.0.1:5554
Received: Android Console: Authentication required
Android Console: type 'auth <auth_token>' to authenticate
Android Console: you can find your <auth_token> in 
'/Users/testr/.emulator_console_auth_token'
OK

我希望看到的只是 CONNECTED TO: 127.0.0.1:5554

的一个实例

我相信我在某个地方犯了一个错误,关闭了旧连接,但无法理解在哪里。

如果服务器已启动:

在第一次尝试中,身份验证工作正常:

CONNECTED TO: 127.0.0.1:5554
Received: Android Console: Authentication required
Android Console: type 'auth <auth_token>' to authenticate
Android Console: you can find your <auth_token> in 
'/Users/testr/.emulator_console_auth_token'
OK

连接重试:

Connection refused, device not up yet..
Retrying..
Connection closed
CONNECTED TO: 127.0.0.1:5554
CONNECTED TO: 127.0.0.1:5554
Received: Android Console: Authentication required
Android Console: type 'auth <auth_token>' to authenticate
Android Console: you can find your <auth_token> in 
'/Users/testr/.emulator_console_auth_token'
OK

const net = require('net');
const HOST = '127.0.0.1';
const Port = 5554;
let client = new net.Socket();


    // connection
     const conn = function Connect(Port) {
         client.connect(Port, '127.0.0.1', function () {
            console.log('CONNECTED TO: ' + '127.0.0.1' + ':' + Port);
             client.write('auth testcred');
        });
    };

     // error handling
    client.on('error', function (error) {
        if (error.code === 'ECONNREFUSED') {
            console.log("Connection refused, device not up yet..");
            console.log("Retrying..");
            setTimeout(function() {
                conn(Port);
            }, 10000);
        }
    });

    // on response from server
    client.on('data', function(data) {
        console.log('Received: ' + data);
        client.destroy();
        client.removeAllListeners();
    });

    // on connection closure
    client.on('close', function() {
        console.log('Connection closed');
        client.destroy();
    });


     conn(Port);


我希望输出仅 return CONNECTED TO: 127.0.0.1:5554 一次,但我看到它的打印次数等于重试次数。

可能发生的情况是:

  1. 您只有一个插座,并且:
  2. 它一次只经历一个连接,但是:
  3. 您在套接字上注册了多个 connectListeners。每次您调用 connect() 都会注册一个新的,并且列表会越来越长。

参考。 docs:

connectListener Common parameter of socket.connect() methods. Will be added as a listener for the 'connect' event once.

在这种情况下,文档给出的建议(使用 net.createConnection() 打开套接字)可能是合适的。与其给 client 一个较长的生命周期,你最好在每次你想开始一个新的连接时更换它。