我正在尝试将传感器信息从 NodeJs 实例发送到另一个(最终在另一台服务器上)。当下面客户端代码中的 while 循环启用时,不会向服务器发送连接或数据。然而,当 while 循环被注释掉时,我得到一个连接和数据。它只是一个单一的数据对象,但当不在循环中拉取传感器数据时,这是可以预期的。
服务器代码:
'use strict';
const net = require('net');
const PORT = 5000;
const ADDRESS = '127.0.0.1';
let server = net.createServer(onClientConnected);
server.listen(PORT, ADDRESS);
function onClientConnected(socket) {
console.log(`New client: ${socket.remoteAddress}:${socket.remotePort}`);
socket.destroy();
}
console.log(`Server started at: ${ADDRESS}:${PORT}`);
function onClientConnected(socket) {
let clientName = `${socket.remoteAddress}:${socket.remotePort}`;
console.log(`${clientName} connected.`);
socket.on('data', (data) => {
let m = data.toString().replace(/[\n\r]*$/, '');
var d = {msg:{info:m}};
console.log(`${clientName} said: ${data.toString()}`);
socket.write(`We got your message (${m}). Thanks!\n`);
});
socket.on('end', () => {
console.log(`${clientName} disconnected.`);
});
客户代码:
var n = require('net');
var s = n.Socket();
s.connect(5000, 'localhost');
var i2c = require('i2c-bus');
var MPU6050 = require('i2c-mpu6050');
var address = 0x68;
var i2cl = i2c.openSync(1);
var sensor = new MPU6050(i2cl, address);
//while (true) {
var data = sensor.readSync();
console.log(data);
s.write(data.toString());
//}