【问题标题】:Node.JS raw socket: how to do repeated connect-disconnect?Node.JS 原始套接字:如何重复连接断开?
【发布时间】:2017-12-08 13:09:18
【问题描述】:

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

  1. 连接到设备
  2. 发送“数据”。
  3. 有200msec的延迟,保证对方收到数据并且已经回复。
  4. 处理数据
  5. 断开连接。
  6. 等待 1 秒
  7. 回到 1。

这个 1-time 连接代码有效(我从网上得到的):

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

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

【问题讨论】:

    标签: node.js raw-sockets


    【解决方案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
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 2013-12-31
      • 2018-05-05
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多