繁体   English   中英

将 SSE 与 NodeJs 一起使用时的多个 http 请求

[英]Multiple http requests while using SSE with NodeJs

我正在尝试实现一个应用程序,我需要做的一件事是使用服务器发送事件将数据从服务器发送到客户端。 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

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

你们中有人知道如何解决这个问题吗? 先感谢您。

这样做的方法是不包括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()将数据发送到连接的客户端。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM