Skip to content

Instantly share code, notes, and snippets.

@grantmichaels
Forked from matheustardivo/chat.html
Created May 13, 2012 20:51
Show Gist options
  • Save grantmichaels/2690120 to your computer and use it in GitHub Desktop.
Save grantmichaels/2690120 to your computer and use it in GitHub Desktop.
Simple Chat app using Node.js and Redis
<!DOCTYPE html>
<html>
<head>
<title>Node.js chat</title>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript" src="/nowjs/now.js"></script>
<script type="text/javascript">
$(document).ready(function() {
now.receiveMessage = function(time, name, message) {
$("#messages").append("<br />[" + time + "] &lt" + name + "&gt: " + message);
};
now.addName = function(name) {
$("#names").append("<li>" + name + "</li>");
};
$("#send-button").click(function() {
now.distributeMessage($("#text-input").val());
$("#text-input").val("");
});
$("#text-input").keyup(function(event) {
if (event.which == 13) {
now.distributeMessage($("#text-input").val());
$("#text-input").val("");
}
});
now.name = prompt("What's your name?");
$("#welcome").append("Welcome " + now.name);
});
</script>
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<div class="page-header">
<h2>Names</h2>
</div>
<ul id="names"></ul>
</div>
<div class="span8">
<div class="page-header">
<h1 id="welcome"></h1>
</div>
<div id="messages"></div>
<hr />
<div class="well">
<input type="text" id="text-input" class="span8">
<input type="button" value="Send" id="send-button" class="btn-primary">
</div>
</div>
</div>
</div>
</body>
</html>
var connect = require("connect");
var nowjs = require("now");
var redis = require("redis"),
client = redis.createClient();
var server = connect()
.use(connect.favicon())
.use(connect.logger())
.use(connect.static("public"))
.listen(8888);
var chat = nowjs.initialize(server);
client.del("names", redis.print);
client.del("messages", redis.print);
chat.connected(function() {
console.log("Connected => ", this.now.name);
chat.now.addName(this.now.name);
var self = this;
client.lrange("messages", 0, -1, function(err, replies) {
console.log("Messages length => ", replies.length);
replies.forEach(function(reply, i) {
var msg = JSON.parse(reply.toString());
self.now.receiveMessage(msg.time, msg.name, msg.text);
});
});
client.lrange("names", 0, -1, function(err, replies) {
console.log("Names length => ", replies.length);
replies.forEach(function(reply, i) {
self.now.addName(reply.toString());
});
});
client.lpush("names", this.now.name);
});
chat.now.distributeMessage = function(message) {
var msg = {
time: new Date().toLocaleTimeString(),
name: this.now.name,
text: message
}
chat.now.receiveMessage(msg.time, msg.name, msg.text);
client.lpush("messages", JSON.stringify(msg));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment