【发布时间】:2017-12-08 13:09:18
【问题描述】:
目前我正在尝试反复连接和断开设备(TCP 套接字)。这是流程
- 连接到设备
- 发送“数据”。
- 有200msec的延迟,保证对方收到数据并且已经回复。
- 处理数据
- 断开连接。
- 等待 1 秒
- 回到 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