我有一个Node.JS服务器,它侦听两个端口。标准 HTTP 位于端口 3000 上,它提供了一个具有两条路由的 API:/getInfo
和 /sendCommand
。我在 3001 上有一个特定协议的侦听器,其中连接了设备。目标是从 Web 界面执行 API 调用并将其发送到设备以接收输出。像这样:
GET localhost:3000/getInfo
server sends command to the device connected on localhost:3001
server receives some output
server responses to the request
由于 Node.JS 请求和响应与其他服务器异步,代码应该是什么样子的?
设备服务器:
var raspberryList = [];
function sendCommand(name, command) {
for (var i = 0; i < raspberryList.length; i++) {
if (!raspberryList[i].name.localeCompare(name)) {
raspberryList[i].write(command);
}
}
}
var server = net.createServer(function(socket) {
socket.name = socket.remoteAddress;
console.log(socket.name + " joined.";
raspberryList.push(socket);
socket.on('data', function(data) {
// TODO: Data received here should be displayed into the web interface
console.log(socket.name + " > " + data);
});
socket.on('end', function() {
raspberryList.splice(raspberryList.indexOf(socket), 1);
console.log(socket.name + " left.");
});
});
节点.JS API 路由:
app.post('/getInfo', function(req, res) {
// TODO: send the command somehow and get the output
// Send the response
res.send(response);
});
如果您在端口 3001 上使用 HTTP,则可以尝试使用 request。
var request = require('request');
app.post('/getInfo', function(req, res) {
request('http://localhost:3000/endpoint', function (error, response, body) {
if (error) throw error;
res.send(body);
});
});