I'm attempting to setup a node js server to stream some events via SSE and I cannot get it to work unless I start the stream with the data
field.
When i try and include other fields for example id
or event
they dont show in the chrome inspector?
If I attempt to put these field before data no events other than the connection opening occurs.
Here is the route that I am playing around with.
router.get('/stream', function * (){
let stream = new PassThrough();
let send = (message, id) => stream.write(`id: ${JSON.stringify(id)}\n data: ${JSON.stringify(message)}\n\n`);
let finish = () => dispatcher.removeListener('message', send);
this.socket.setTimeout(Number.MAX_VALUE);
this.type = 'text/event-stream;charset=utf-8';
this.set('Cache-Control', 'no-cache');
this.set('Connection', 'keep-alive');
this.body = stream;
stream.write(': open stream\n\n');
dispatcher.on('message', send);
this.req.on('close', finish);
this.req.on('finish', finish);
this.req.on('error', finish);
setInterval(function(){
dispatcher.emit('message', {date: Date.now()}, '12345')
}, 5000)
});
I am not too certain if I am writing to the stream correctly.
Thanks
Silly me, it was indeed a malformed event stream. There isnt supposed to be a space between the fields. It should instead be:
id: ${JSON.stringify(id)}\\ndata: ${JSON.stringify(message)}\\n\\n
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.