英文:
Send server intern messages between http request and websocket
问题
以下是翻译好的部分:
我有一个微控制器,它向一个Node.js HTTP服务器发送数据。当微控制器发出HTTP请求时,我想通过WebSocket连接向Web客户端发送一条消息。
这是我的路由:
const express = require("express");
const router = express.Router();
router.route("/sendData").post(async (req, res) => {
//一些验证
//在这里,我想要启动一条消息,通过WebSocket发送给Web客户端
return res.status(200).json({ message: "已发送数据到服务器" });
});
module.exports = router;
然后,我有一个示例WebSocket服务器:
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
//在这里,当微控制器发出HTTP请求时,我想向客户端发送一条消息
ws.send('已接收数据');
});
现在,我该如何在HTTP路由和WebSocket服务器之间建立通信?我对Node.js中的进程处理不太熟悉。我是否需要类似于node-ipc的东西?
英文:
I have a microcontroller which sends data to an node js http server. I want to send a message to a web client through a websocket connection, when the microcontroller hits the http request.
This is my route:
const express = require("express");
const router = express.Router();
router.route("/sendData").post(async (req, res) => {
//some validation
//Here I want to initiate a message which gets sent to a web client through a websocket
return res.status(200).json({ message: "sent data to server")};
});
module.exports = router;
Then i have a example websocket server:
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
//here i want to send a message to a client when the microcontroller hits the http request
ws.send('data received');
});
Now, how can i create communication between the http-route and the websocket server? I am new to the handling of processes in node js. Do I need something like node-ipc?
答案1
得分: 0
以下是翻译好的部分:
- 不要创建2个独立的脚本,而是将你的Express服务器和WebSocket服务器合并在一个进程中。(你仍然可以将这两个服务器拆分到多个文件中,但关键是你希望它们都从同一个Node实例中运行)。
- 创建一个(全局)EventEmitter。
- 当收到HTTP请求时,使用这个事件发射器来
emit
某个事件。 - WebSocket使用EventEmitter上的
.on()
来订阅事件。当它们触发时,发送消息回去。 - 确保在WebSocket连接关闭时调用
.off()
,以防止内存泄漏。
英文:
Probably the easiest way to get started with this is to:
- Don't create 2 separate scripts, but combine both your express server and websocket server in 1 process. (You can still split up these 2 servers in multiple files, but the point is you want them both running from the same node instance).
- Create a (global) EventEmitter.
- When a HTTP request comes in, you use this event emitter to
emit
some event. - The WebSocket uses
.on()
on the EventEmitter to subscribe to events. When they trigger, send the message back. - Make sure you call
.off()
when the websocket connection closes so you don't create memory leaks.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论