Javascript 重试时客户端连接未正确关闭
我有一个小型测试telnet客户端,它需要对android设备执行身份验证。它工作正常,但是我想了解这种方法是否正确&不会导致内存泄漏 我认为此脚本可能导致内存泄漏的原因是,当在REFIRES上建立连接时,我看到多个连接确认:Javascript 重试时客户端连接未正确关闭,javascript,android,node.js,telnet,Javascript,Android,Node.js,Telnet,我有一个小型测试telnet客户端,它需要对android设备执行身份验证。它工作正常,但是我想了解这种方法是否正确&不会导致内存泄漏 我认为此脚本可能导致内存泄漏的原因是,当在REFIRES上建立连接时,我看到多个连接确认: 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:
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
连接重试时:
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
我希望输出只返回连接到:127.0.0.1:5554的
一次,但我看到它打印出来的次数等于重试次数。可能发生的情况是:
您只有一个插座,并且:
它一次只经历一个连接,但是:
您在套接字上注册了多个connectListeners
。每次您调用connect()
,都会注册一个新的,而且列表会越来越长
参考文件:
connectListener
socket.connect()方法的公共参数。将作为“连接”事件的侦听器添加一次
在这种情况下,文档给出的建议(使用net.createConnection()
打开套接字)可能是合适的。与其让客户机
有很长的使用寿命,不如在每次想开始新连接时都更换它。谢谢@greeble31,这很有意义,我将修改我的方法。非常感谢,干杯!
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);