【问题标题】:Multiple http requests while using SSE with NodeJs将 SSE 与 NodeJ 一起使用时的多个 http 请求
【发布时间】:2020-04-18 17:51:24
【问题描述】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-07-28
      • 1970-01-01
      • 2013-03-17
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多