Created
March 18, 2016 02:38
-
-
Save seungha-kim/87baed597c23e14b83be to your computer and use it in GitHub Desktop.
Simple SSE on node.js
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
var express = require('express'); | |
var EventEmitter = require('events'); | |
var bodyParser = require('body-parser'); | |
var app = express(); | |
var messageRouter = new EventEmitter(); | |
app.use(bodyParser.urlencoded({ extended: false })); | |
app.use(express.static('.')); | |
app.post('/message', function(req, res) { | |
console.log(`message arrived : ${JSON.stringify(req.body)}`); | |
messageRouter.emit('message', req.body); | |
res.json({ok: true}); | |
}); | |
// SSE middleware | |
function eventSource (req, res, next) { | |
res.writeHead(200, { | |
'Connection': 'keep-alive', | |
'Content-Type': 'text/event-stream', | |
'Cache-Control': 'no-cache' | |
}); | |
res.on('close', function (e) { | |
console.log('connection ends'); | |
}); | |
next(); | |
} | |
// SSE handler | |
app.get('/updates', eventSource, function(req, res) { | |
messageRouter.on('message', function (body) { | |
res.write(`data: ${JSON.stringify(body)}\n\n`); | |
}) | |
}); | |
setInterval(function () { | |
messageRouter.emit('message', {heartbeat: true}); | |
}, 30000); | |
var port = 5000; | |
app.listen(port, function() { | |
console.log(`listening on port ${port}...`); | |
}); |
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
<!doctype html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
</head> | |
<body> | |
<div id="messages"></div> | |
<script> | |
var es = new EventSource('http://localhost:5000/updates'); | |
es.addEventListener('message', function (e) { | |
console.log(e); | |
var p = document.createElement('p'); | |
p.textContent = JSON.parse(e.data).message; | |
document.querySelector('#messages').appendChild(p); | |
}) | |
</script> | |
</body> | |
</html> |
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
{ | |
"author": "Seungha Kim", | |
"dependencies": { | |
"body-parser": "^1.15.0", | |
"express": "^4.13.4" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment