Skip to content

Instantly share code, notes, and snippets.

@juev
Forked from matthewfl/chat.index.html
Created June 26, 2011 10:59
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 juev/1047517 to your computer and use it in GitHub Desktop.
Save juev/1047517 to your computer and use it in GitHub Desktop.
A really basic chat server on http://chat.jsapp.us
<html>
<head>
<title>Chat</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(function () {
function check () {
$("#output").load('/update', function () {
setTimeout(check, 1);
});
}
function send () {
$.post("/send", $("#text").val());
$("#text").val('');
}
check();
$("#send").click(send);
$("#text").keypress(function (e) {
if(e.keyCode == 13) send();
})
});
</script>
</head>
<body>
<h3>This is a really simple demo that I wrote to quickly test out jsapp.us, the code is only about 15 lines longs and uses node-router</h3>
<p>I came back and added long polling, it took about 15 min</p>
<div id="output">{text}</div>
<br>
<input id="text"></input><button id="send">Send</button>
<br>
<a href="https://gist.github.com/713200">Code</a>
</body>
</html>
// chat application
var db = require('db');
var router = require('./node-router'),
server = router.getServer(),
fs = require('fs');
var updates = [];
var clients = [];
var fileContent = null;
server.get('/', function (req, res) {
if(fileContent) {
return fileContent.replace("{text}", "<p>"+updates.join("</p><p>")+"</p>")
}else{
fs.readFile('chat.index.html', function (err, content) {
res.writeHead(200, {"Content-type": "text/html"});
res.end(content.replace("{text}", ""));
fileContent = content;
});
}
});
server.get('/update', function (req, res) {
res.writeHead(200, {"Content-type":"text/html"});
clients.push(res);
});
server.post('/send', function (req, res) {
var data="";
req.on('data', function (d) {
data += d.toString('ascii');
});
req.on('end', function () {
updates.push(data);
res.end();
var t = "<p>"+updates.join("</p><p>")+"</p>";
while(clients.length) {
clients.pop().end(t);
}
})
});
server.listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment