目前我正在尝试重复连接和断开设备(TCP套接字)。这是流程
这个一次性连接代码正在运行(我是从网上获得的):
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 23;
// (a) =========
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('data');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
// (b) =========
目前,上述代码适用于1次连接。我确实将(a)到(b)中的代码放在while(true)循环中,并使用https://www.npmjs.com/package/sleep在最后放置了1秒的睡眠,似乎连接没有在该设置上执行。 / p>
对此的任何想法都会有所帮助。
答案 0 :(得分:2)
我认为最好的方法是在函数“loopConnection”中封装你想要做的事情,并在每个client.on('close')
上递归调用,如下所示:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 23;
var loopConnection = function() {
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('data');
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
setTimeout(function() {
loopConnection(); // restart again
}, 1000); // Wait for one second
});
};
loopConnection(); // Initialize and first call loopConnection
希望它有所帮助。