Skip to content

Instantly share code, notes, and snippets.

@19h
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 19h/d9176965e224d263ddb8 to your computer and use it in GitHub Desktop.
Save 19h/d9176965e224d263ddb8 to your computer and use it in GitHub Desktop.
var http = require("http"), fs = require("fs");
var index_buf = fs.readFileSync("./index.html");
http.createServer(function (req, res) {
var isClosed;
if (req.url === "/" || req.url === "/index.html") {
res.write(index_buf);
}
switch (req.url) {
case "/":
case "/index.html":
return res.end(index_buf);
case "/sse":
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
});
var next = function () {
if (isClosed) return;
if (req.readable && res.writable) {
res.write("data: " + Math.random() + "\n\n");
setTimeout(next, 100);
}
}
res.write('event: dipshit\n');
next();
}
res.on("close", function () {
isClosed = true;
});
res.on("error", function () {
isClosed = true;
});
}).listen(8080);
<html>
<head>
<title>howdy dipshit hypfer</title>
<script type="text/javascript">
;(function () {
var tarm;
(function connect() {
tarm = new EventSource("/sse");
tarm.onmessage = function(e) {
document.querySelector("section").innerText = e.data;
}
tarm.onerror = connect;
})();
})();
</script>
</head>
<body>
<section></section>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment