简体   繁体   中英

Multiple http requests while using SSE with NodeJs

I'm trying to implement an application and one of the things I need to do is to use Server Sent Events to send data from the server to the client. The basis of SSE is to have one connection in which data is transfered back and forth without this connection being closed. The problem I'm having right now is that everytime I make a HTTP from the client using EventSource() multiple request are being made.

Client:

 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)
 }       

Server (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 is what I see in the chrome dev tools. When the client tries to connect using SSE, it makes multiple requests to the server. However only one request was supposed to made.

Do any of you know how to fix this? Thank you in advance.

The way one would do that is to not include the res.end() since the connection has to be kept alive. On top of that, I had to keep track of the responses from the http requests made by the user, so I created a different module with the following methods:

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`) 
    }
}

This way one can access the response objects and use the function update() to send data to the connected clients.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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