我正在尝试实现一种方法,在每次命中服务器端点时在NodeJs中发送服务器发送事件(SSE)。
这就是我是如何做到的
//...code...
import EventSource from "eventsource";
const EventEmitter = require('events');
const events = new EventEmitter();
// events.setMaxListeners(10);
// api end point route from where the new order requests will be coming
router.route('/new-order')
.post((req, res) => {
const orderData = req.body.data;
//... save order and emit an event to send response to the client react app
events.emit('newOrder', orderData);
});
// define a function to send SSE events to the client
const sse = res => data => {
const dataToSend = JSON.stringify(data);
res.write(`data:${dataToSend}`);
res.write("\n\n");
};
// define an EventSource route for the client to be connected for new events
router.route('/sse')
.get((req, res) => {
res.writeHead(200, {
"Connection": "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
});
res.write("\n");
const sendSSE = sse(res);
/*
PROBLEMATIC CODE-- EACH request to /sse route adds new event listener,
and in minutes, it exceeds the limit of maxListeners, and I get the warning
to increase the max event listeners limit by using setMaxListeners()
even if only 1 user is using the front end app.
*/
events.on('newOrder', sendSSE);
});
//...Code...
// Client Side
const newOrderReceived = (e) => {
console.log(JSON.parse(e.data));
};
if ( !window.eventSource ) {
window.eventSource = new EventSource('https://example.com/sse');
window.eventSource.onmessage = newOrderReceived;
}但问题是,maxListeners的排气速度非常快,即使只有一个用户正在使用该应用程序。
如果我将事件绑定代码更改为
events.once('newOrder', sendSSE);事件maxListeners错误消失,但它没有通知我的应用程序后,第一次订购。我无法找到将事件绑定到我的/sse路由之外的方法,因为我需要通过
res.write(`data:${dataToSend}`);
res.write("\n\n");而且,在我的例子中,res对象仅在路由中可用-- /sse。
这个问题的解决方案是什么?还是有更好的方法在NodeJS中发送服务器发送事件(SSE)通知我的前端应用程序,每次我在API端点上收到请求时?
任何帮助都将不胜感激。
P.S:我在搜索这个问题时看到的所有教程/指南都是在发送数据的路由内实现setInterval,我没有找到一个教程来解释如何针对服务器上的事件发送数据。
发布于 2020-04-15 11:28:37
下面是我解决这个问题的方法
// Events.js File
const EventEmitter = require('events');
const events = new EventEmitter();
events.setMaxListeners(parseInt(config.MAX_EVENT_LISTENERS));
events.on('error', (err) => {
// handle Error
});
// event to fire on each new order.
events.on('newOrder', (data) => {
// and in the events.js file, I access it from the global scope of Node
// so this is the `res` object from the route where I want to send SSE.
if ( global.sseResponse ) {
const sendSSE = sse(global.sseResponse);
sendSSE(data);
} else {
// no sse listener, do something else,
}
});
module.exports = events;在我的路线档案里
// My routes file where I want to use this
router.route('/sse')
.get(
(req, res) => {
res.writeHead(200, {
"Connection": "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
});
res.write("\n");
// Node has a global variable as browsers have a window variable, I attached the res object of my route to
// the Node's global object to access it outside of this route
global.sseResponse = res;
const sendSSE = ApiController.sse(res);
// keep the connection on
setInterval(() => {
sendSSE({ message: 'keep-connection-alive' });
}, 5000);
});下面是我用来发送sse的函数,您可以将它写到任何您想要的地方,然后从那里导出它以便在多个地方使用
// function to send server sent events (sse)
const sse = res => data => {
const dataToSend = JSON.stringify(data);
res.write(`data:${dataToSend}`);
res.write("\n\n");
// this is the important part if using the compression npm module
res.flush();
},用这种方法解决了我的问题,希望它也能帮助别人。
https://stackoverflow.com/questions/58969364
复制相似问题