Skip to content

Instantly share code, notes, and snippets.

@karenpeng
Last active March 19, 2019 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karenpeng/c1afab1942416c1fbe355f519d9f7540 to your computer and use it in GitHub Desktop.
Save karenpeng/c1afab1942416c1fbe355f519d9f7540 to your computer and use it in GitHub Desktop.
/* On the server side, when get the request from eventSource,
* response with content type as 'text/event-stream',
* and write data in the format according to
* https://www.w3.org/TR/2009/WD-eventsource-20090421/
*/
const constructSSEMsg = (res, id, data) => {
res.write('id: ' + id + '\n');
res.write('data: ' + data + '\n\n');
};
const handleSSErequest = () => {
app.get('/sse', (req, res) => {
res.writeHead(200, {
'Connection': 'keep-alive',
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache'
});
const id = new Date();
let counter = 0;
setInterval(() => {
constructSSEMsg(res, id, JSON.stringify({
random: Math.random(),
sequence: counter
}));
counter++;
}, 3000);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment