Last active
March 19, 2019 08:01
-
-
Save karenpeng/c1afab1942416c1fbe355f519d9f7540 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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