Server Sent Events Delay



问题:有些事件需要1/2分钟才能到达客户端。

设置:我有一个nodejs后端试图使用SSE发送事件到React应用程序客户端,而有nginx作为代理。使用fargate任务和负载平衡器部署在aws中。

事件最终到达客户端,但花费了大量时间,使得它对我的用例毫无用处。

后端代码:

Endpoint to start connection:
handler: async (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})

const id = Date.now()
const data = { id, response: res }
emitterList.push(data) // array with the responses

setTimeout(() => {
res.end()
remove(id)
}, 2 * 60 * 1000)

req.on('close', () => { remove(id) })
}
Endpoint to push data to connected clients
emitterList
.forEach(elem => {
try {
console.log('WRITE: ', new Date())
elem.response.write(`data: ${JSON.stringify(data)}`)
elem.response.write(`nn`)
} catch(err) { 
deadEmitters.push(elem.id) 
}
removeDeadEmitters()

客户机代码:

const eventSource = new EventSource(`${process.env.REACT_APP_BACKEND_BASE_URL}/emitter/${id}`)
eventSource.onmessage = (e) => { console.log(new Date()) }

我需要在nginx中设置任何配置吗?

解决方案是在响应中添加标题'X-Accel-Buffering': 'no'。