Skip to content

Instantly share code, notes, and snippets.

@JustinBeckwith
Created November 6, 2015 22:42
Show Gist options
  • Save JustinBeckwith/3c10dcb22c02e9d9ec08 to your computer and use it in GitHub Desktop.
Save JustinBeckwith/3c10dcb22c02e9d9ec08 to your computer and use it in GitHub Desktop.
Quick example of server side events in nodejs
<!DOCTYPE html>
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script src='http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js'></script>
<script>
var source = new EventSource('/streeeem');
source.addEventListener('message', function(e) {
console.log(e);
$('ul').append('<li>' + e.data + ' (message id: ' + e.lastEventId + ')</li>');
}, false);
</script>
</head>
<body>
<ul></ul>
</body>
</html>
{
"version": "0.0.0",
"dependencies": {
"express": "latest"
}
}
var express = require('express');
var http = require('http');
var app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/public/index.html');
});
app.get('/streeeem', function(req, res) {
console.log('hey there, got some streeem');
req.socket.setTimeout(Number.MAX_VALUE);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
var cnt = 0;
setInterval(function() {
res.write('id: ' + (cnt++) + '\n');
res.write("data: " + "message" + '\n\n');
}, 2000)
});
http.createServer(app).listen(process.env.PORT || 8080, function() {
console.log('Listening on %d', this.address().port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment