Node.JS 原始套接字:重复连接断开怎么办?

Node.JS raw socket: how to do repeated connect-disconnect?

目前我正在尝试反复连接和断开设备(TCP 套接字)。这是流程

  1. 连接到设备
  2. 发送一个"data".
  3. 有200msec的延时,保证对方收到数据,已经回复
  4. 处理数据
  5. 断开连接。
  6. 等待1秒
  7. 返回 1。

此 1 次连接代码有效(我从网上获取):

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 秒的睡眠,看起来连接没有在该设置上执行。

对此的任何想法都会有所帮助。

我认为最好的方法是将你想做的事情封装在一个函数 "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

希望对您有所帮助。