【发布时间】:2023-04-04 09:08:01
【问题描述】:
我有一个小型测试 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);
我希望输出只返回一次CONNECTED TO: 127.0.0.1:5554,但我看到它打印的次数等于重试次数。
【问题讨论】:
标签: javascript android node.js telnet