Skip to content

Instantly share code, notes, and snippets.

@yanai101
Last active December 2, 2018 09:03
Show Gist options
  • Save yanai101/5cc82c7ab807df60bb48e0d7dd7d5301 to your computer and use it in GitHub Desktop.
Save yanai101/5cc82c7ab807df60bb48e0d7dd7d5301 to your computer and use it in GitHub Desktop.
express sse example
/// server ///
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.status(200).set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
const data = {
message: 'hi all'
}
const intv = setInterval(()=>{
data.timestapm = Date.now();
// you have to add 'data: ... ' and in the end '\n\n' - otherwise in the client side - the on message - not calld
// do you one logic when to stap the bordcast
res.write(`data: ${JSON.stringify(data)} \n\n`);
res.write(`event: messageType \n`); // optional
res.write(`id: messageID \n`); // optional
}, 2000)
});
module.exports = router;
<html>
<head>
<title>Express</title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>Express SSE</h1>
<button onclick="start()">start SSE</button>
<button onclick="stop()">stop SSE</button>
<ul id="eventlist"> </ul>
<script>
const eventList = document.getElementById("eventlist");
let evtSource = null;
function start(){
evtSource = new EventSource("http://localhost:3000/api");
evtSource.onopen = () => console.log('%c Open connection sse', 'color: blue; background: yellow')
evtSource.onmessage = function(e) {
console.log("received event");
console.log(e);
const newElement = document.createElement("li");
newElement.innerHTML = "message: " + e.data;
eventList.appendChild(newElement);
};
// evtSource.addEventListener('message', event => {
// const data = JSON.parse(event.data);
// console.log('getDATA')
// })
evtSource.onerror = function(e) {
console.log("%c EventSource failed." , 'color:red');
};
}
function stop(){
if(evtSource) evtSource.close();
evtSource = null;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment