Skip to content

Instantly share code, notes, and snippets.

@andy12530
Created October 24, 2012 03:16
Show Gist options
  • Save andy12530/3943467 to your computer and use it in GitHub Desktop.
Save andy12530/3943467 to your computer and use it in GitHub Desktop.
EventSource Demo【SSE】
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Chat Demo</title>
<style type="text/css">
form {
width: 600px;
margin: 0 auto;
}
</style>
<script type="text/javascript">
window.onload = function() {
var input = document.getElementById("msgInput");
input.focus();
var chat = new EventSource("/chat");
chat.onmessage = function(event) {
console.log(chat);
var msg = event.data;
var node = document.createTextNode(msg);
var div = document.createElement("li");
div.appendChild(node);
document.getElementById("message").appendChild(div);
}
input.onchange = function() {
var msg = "Andy" + ":" + input.value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "/chat");
xhr.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
xhr.send(msg);
input.value = "";
}
};
</script>
</head>
<body>
<form action="">
<label for="msg">Message:</label></br>
<textarea name="msg" id="msgInput"></textarea>
</form>
<div id="message">
</div>
</body>
</html>
var http = require("http");
var clientUI = require("fs").readFileSync("clientChat.html");
var clients = [];
setInterval(function() {
clients.forEach(function(client) {
client.write(":ping\n");
});
}, 1000);
var server = new http.Server();
server.on("request", function(req, res) {
var url = require("url").parse(req.url);
if(url.pathname == "/") {
res.writeHead(200, {"Content-Type": "text/html"});
//res.write("<script>" + emulation + "</script>");
res.write(clientUI);
res.end();
return;
} else if(url.pathname !== "/chat") {
res.writeHead(404);
res.end("Not Found!");
return;
}
if(req.method === "POST") {
console.log("OK POST");
req.setEncoding("utf8");
var body = "";
req.on("data", function(chunk) {
body += chunk;
});
req.on("end", function() {
res.writeHead(200);
res.end();
message = "data:" + body.replace('\n', '\ndata:') + "\r\n\r\n";
clients.forEach(function(client) {
console.log(message);
client.write(message);
});
});
} else {
res.writeHead(200, {"Content-Type": "text/event-stream"});
res.write("data:Connected\n\n");
req.connection.on("end", function() {
clients.splice(clients.indexOf(res), 1);
res.end();
});
clients.push(res);
}
});
server.listen(1333);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment