Created
March 6, 2013 02:47
-
-
Save g-k/5096313 to your computer and use it in GitHub Desktop.
Old server-sent event hello world timer test.
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> | |
<script> | |
var source = new EventSource('/events'); | |
source.onmessage = function(e) { | |
document.body.innerHTML += e.data + '<br>'; | |
}; | |
</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
var fs = require('fs'); | |
var http = require('http'); | |
var sys = require('sys'); | |
var url = require('url'); | |
function debugHeaders(req) { | |
sys.puts('URL: ' + req.url); | |
for (var key in req.headers) { | |
sys.puts(key + ': ' + req.headers[key]); | |
} | |
sys.puts('\n\n'); | |
} | |
var port = 8000; | |
var ip = "localhost"; | |
http.createServer(function(req, res) { | |
debugHeaders(req); | |
var uri = url.parse(req.url).pathname; | |
console.log(uri); | |
if (req.headers.accept && req.headers.accept == 'text/event-stream') { | |
if (req.url == '/events') { | |
sendSSE(req, res); | |
} else { | |
res.writeHead(404); | |
res.end(); | |
} | |
} else { | |
res.writeHead(200, {'Content-Type': 'text/html'}); | |
res.write(fs.readFileSync(__dirname + '/index.html')); | |
res.end(); | |
} | |
}).listen(port, ip); | |
console.log('Running HTTP server at:', ip, ':', port); | |
function sendSSE(req, res) { | |
res.writeHead(200, { | |
'Content-Type': 'text/event-stream', | |
'Cache-Control': 'no-cache', | |
'Connection': 'keep-alive' | |
}); | |
var id = (new Date()).toLocaleTimeString(); | |
// Sends a SSE every 5 seconds on a single connection. | |
setInterval(function() { | |
constructSSE(res, id, (new Date()).toLocaleTimeString()); | |
}, 5000); | |
constructSSE(res, id, (new Date()).toLocaleTimeString()); | |
} | |
function constructSSE(res, id, data) { | |
console.log("Sending:", id, data); | |
res.write('id: ' + id + '\n'); | |
res.write("data: " + data + '\n\n'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment