使用带有NodeJ的SSE时有多个http请求

问题描述 投票:1回答:1

我正在尝试实现应用程序,我需要做的一件事情就是使用服务器发送事件将数据从服务器发送到客户端。 SSE的基础是建立一个连接,该连接可以在不关闭该连接的情况下来回传输数据。我现在遇到的问题是,每次使用EventSource()多个请求从客户端发出HTTP时。

客户:

 const eventSource = new EventSource('http://localhost:8000/update?nick='+username+'&game='+gameId)
 eventSource.onmessage = function(event) {
        const data = JSON.parse(event.data)
        console.log(data)
 }       

服务器(Node.Js):

case '/update':
      res.writeHead(200,{
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
      })
     res.write('data: 1')
     res.write('\n\n')
     res.end('{}')
 break

This是我在chrome开发工具中看到的。当客户端尝试使用SSE进行连接时,它将向服务器发出多个请求。但是应该只提出一个请求。

你们都知道如何解决这个问题吗?预先谢谢你。

node.js http server-sent-events
1个回答
0
投票

这样做的方法是不包含res.end(),因为必须保持连接有效。最重要的是,我必须跟踪用户发出的http请求的响应,因此我使用以下方法创建了一个不同的模块:

let responses = []

module.exports.remember = function(res){
    responses.push(res)
}

module.exports.forget = function(res){
    let pos = responses.findIndex((response)=>response===res)
    if(pos>-1){
        responses.splice(pos, 1)
    }
}

module.exports.update = function(data){
    for(let response of responses){
        response.write(`data: ${data} \n\n`) 
    }
}

通过这种方式,可以访问响应对象并使用功能update()将数据发送到连接的客户端。

© www.soinside.com 2019 - 2024. All rights reserved.