我有一个小型的测试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
的一个实例
我相信我在某个地方犯了一个错误,无法关闭旧的连接,但无法理解在哪里。
如果服务器已启动:
在第一次尝试中,auth工作正常:
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);
我希望输出仅返回一次CONNECTED TO: 127.0.0.1:5554
,但是我看到它的输出等于重试的次数。
答案 0 :(得分:1)
可能正在发生的事情:
connectListeners
。每次您拨打connect()
时,都会注册一个新的列表,列表只会越来越长。参考docs:
connectListener
socket.connect()方法的公共参数。一次将被添加为“ connect”事件的侦听器。
在这种情况下,文档给出的建议(用net.createConnection()
打开Socket)可能是适当的。与其延长client
的使用寿命,不如每次启动新连接时都最好更换它。