Skip to content
Browse files

Added redis to the game. Now the messages are stored in redis

  • Loading branch information...
1 parent 9e75c06 commit 99e089ca286d34d8b6385266b373f1b8041fe3f9 @jettro committed Apr 24, 2011
Showing with 47 additions and 1 deletion.
  1. +3 −1 public/javascript/local-socket-io.js
  2. +28 −0 redis.js
  3. +16 −0 socketio.js
View
4 public/javascript/local-socket-io.js
@@ -9,7 +9,9 @@ function message(obj) {
$("#users").prepend("<div class='user'>" + obj.users[i] + "</div>")
}
} else if ('buffer' in obj) {
- for (var j in obj.buffer) message(obj.buffer[j]);
+ for (var j in obj.buffer) {
+ message(obj.buffer[j]);
+ }
} else if ('announcement' in obj) {
$("#message").prepend("<div>" + obj.announcement + "</div>");
} else {
View
28 redis.js
@@ -0,0 +1,28 @@
+// https://github.com/mranney/node_redis
+function Redis() {}
+
+var redis = require("redis");
+var client;
+
+Redis.prototype.storeMessage = function (chatMessage) {
+ initClient();
+ client.lpush("messages",chatMessage);
+ client.quit();
+};
+
+Redis.prototype.obtainMessages = function(callback) {
+ initClient();
+ client.lrange("messages",0,14,function(err, replies) {
+ callback(replies);
+ });
+ client.quit();
+};
+
+function initClient() {
+ client = redis.createClient();
+ client.on("error", function (err) {
+ console.log("Error " + err);
+ });
+}
+
+module.exports = Redis;
View
16 socketio.js
@@ -16,6 +16,16 @@ Socketio.prototype.index = function(req, res) {
var io = require('socket.io');
var buffer = [];
var clients = [];
+var Redis = require('./redis');
+var redis = new Redis();
+
+redis.obtainMessages(function(replies) {
+ replies.forEach(function (reply, i) {
+ var chat = JSON.parse(reply);
+ buffer.push(chat);
+ });
+ buffer.reverse();
+});
Socketio.prototype.init = function(app) {
io = io.listen(app);
@@ -35,6 +45,7 @@ Socketio.prototype.init = function(app) {
buffer.push(msg);
if (buffer.length > 15) buffer.shift();
client.broadcast(msg);
+ io.emit('newMessage',msg);
});
client.on('disconnect', function() {
@@ -44,6 +55,11 @@ Socketio.prototype.init = function(app) {
});
});
+ io.on('newMessage', function(obj) {
+ console.log("Received a new message: %s by %s", obj.chat[1], obj.chat[0]);
+ redis.storeMessage(JSON.stringify(obj));
+ });
+
function removeClient(id) {
delete clients[id];
}

0 comments on commit 99e089c

Please sign in to comment.
Something went wrong with that request. Please try again.