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:
NodeJS version 0.10.28 Thank You for attention. Sorry for bad English.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With