我正在开发一个 gps 跟踪系统,并在 node js 上构建了一个服务器。 这是文件的样子以供引用。
const net = require('net');
const lora_packet = require('lora-packet');
const dataParser = require('./dataParser');
const clients = [];
net.createServer(function(socket) {
socket.name = socket.remoteAddress + ":" + socket.remotePort;
clients.push(socket);
socket.on('data', function(data) {
console.log("Buffer sent by terminal : ");
console.log(data);
const packet = lora_packet.fromWire(data, 'hex');
const str = packet._packet.PHYPayload.toString('hex');
dataParser.parse_data(str, socket);
});
socket.on('end', function() {
clients.splice(clients.indexOf(socket), 1);
//broadcast(socket.name + "has left the cartel.\n");
});
function broadcast(message, sender) {
clients.forEach(function(client) {
if (client === sender) client.write(message + "\nsent\n");
return;
client.write(message);
});
process.stdout.write(message);
}
}).listen(8080);
console.log("cartel is running on the port 8080\n");
此服务器文件仅处理来自硬件的请求并处理原始 tcp/ip 请求。
我希望服务器也能处理 http 请求,并希望在服务器中为浏览器的客户端应用程序合并路由功能。
1) 有什么方法可以让同一台服务器处理 http 请求,还是我应该打开另一个端口并在上面部署一个 express node js 应用程序?
2)如果我对http使用同一个8080端口,如何实现路由?
3) 如果我对 http 和原始 tcp/ip 使用不同的端口,那么两个服务器之间通信的最佳方式是什么。 tcp/ip 服务器和 http 服务器之间的通信应该通过套接字(动态发送数据)进行。
从使用 socket 的 http 服务器,数据必须动态发送到浏览器以更新实时位置
那么流量对不对?
硬件(<---->)TCP/IP服务器(<--->)Http服务器(<--->)浏览器
如果需要更多信息来解决查询,我会提供!
谢谢
最佳答案
尝试在同一个端口上使用多种协议(protocol)是非常复杂的。它需要在每个连接开始时采用某种方案来对传入数据进行采样并识别它是哪个协议(protocol),然后将该连接分流到正确的代码来处理该协议(protocol)。我不建议这样做。
只需在不同的端口上打开第二个服务器,让 Express 服务器处理您的 http 请求,这样就简单多了。很简单。您可以在同一个应用程序中完成。因为两个服务器可以在同一个应用程序中,所以您可以直接从一个连接读取并写入另一个连接。不需要进程间通信。
Is there any way that http requests can also be handled by the same server or should I open another port and deploy an express node js app on that?
打开另一个端口。除非您有特定理由使用两个进程,否则无需编写另一个应用程序。您可以将普通 TCP 服务器和 Express 服务器放在同一个 node.js 应用程序中。
If I use the same 8080 port for http, how can the routing be achieved?
这并不容易。不建议对多个协议(protocol)使用相同的端口。
If I use different ports for http and raw tcp/ip, what would be the best way for communication between the two server. The communication between tcp/ip server and http server should happen via socket(sending data dynamically).
您可以将两个服务器放在同一个 node.js 应用程序中,然后您可以使用相同的代码直接从一个服务器读取/写入另一个服务器。不需要进程间通信。
From http server using socket, data has to be sent dynamically to browser to update live location
向浏览器动态发送数据通常意味着您希望浏览器与您的服务器保持类似 webSocket 或 socket.io 的连接,这样您就可以随时通过现有连接向浏览器发送数据。否则,您将不得不“等待”浏览器请求数据,然后在请求时响应数据。
关于javascript - 如何在同一台服务器上处理 tcp/ip 原始请求和 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47825615/