Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSE in node.js doesn't fire "message listener" until res.end(). Reason is in code or

please advice someting. Client code:

var source = new EventSource('/notifications/stream');

    source.addEventListener('open', function(e) {
        console.log('SSE connected')
    }, false);
    source.addEventListener('message', function(e) {
        alert('yes')
        console.log('SSE connected')
    }, false);

Server code

// set timeout as high as possible
req.socket.setTimeout(Infinity);

// send headers for event-stream connection
// see spec for more information
res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
});


res.write('\n');

setInterval(function(){
  console.log('writing');
   res.write("id: " + Date.now()  + "\n");
    res.write("data: " + '{"message":"hello world"} ' + "\n\n");
}, 1000);

And nothing works... but if I add res.end() after res.write() client fires alert() for one time and server crashes because it already ended the res. I read that it might be antivirus's problem that I client doesn't fire until connection is closed, so I turned off antivirus but it didn't help. So my question is:

  1. Is it code problem or other reason (antivirus)
  2. if it's from antivirus, is it for clients antivirus or server's antivirus problem? (I'm developing on Windows with Nod32 antivirus, if I will deploy on linux, will it help or it depends from client's antivirus)
  3. Is there alternative but websocket (my only need is to push notifications with minimum memory usage)

NodeJS version 0.10.28 Thank You for attention. Sorry for bad English.

like image 534
onar Avatar asked Dec 03 '25 15:12

onar


1 Answers

Solved

The problem was in middleware "Compression" that I used in express

Because of the nature of compression this module does not work out of the box with server-sent events. To compress content, a window of the output needs to be buffered up in order to get good compression. Typically when using server-sent events, there are certain block of data that need to reach the client.

You can achieve this by calling res.flush() when you need the data written to actually make it to the client.

like image 173
onar Avatar answered Dec 05 '25 03:12

onar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!