Sunday, March 15, 2015

Codeschool: Real Time Web, Part IV

Sockets I/O

(skipping for now) We're building a chat server. Use socket.io to handle the real-time input/output:
$ npm install --save socket.io
and on the html that uses it:

and here is the code
var express = require('express');
var app = express();

var server = require('http').createServer(app);
var io = require ('socket.io')(server);

io.on('connection',function(client){
  console.log("Client connected");
});
server.listen(8080);

Persisting Data

To keep a log of previous chat messages, we can store the messages in the array:
var message = [];
var storeMessage = function(name,data){
  messages.push({name: name, data: data});
  if (message.length > 1){
    messages.shift()
  }
}
and when a new client joins, we should store the message every time a new message is broadcast. Plus, whenever there is a new connection, we need to give that client all the previous chat messages:
io.sockets.on('connection',function(client){
  ...
  client.on('join',function(name){
    messages.forEach(function(message){
      client.emit("messages",message.name + ": " + message.data);
   });
  });
});
So, how to persist the chat message? DATABASE! Unfortunately they use Redis instead of Postgresql. Anyway, in the hope that this becomes relevant, here is a rewrite of the storeMessage function using redis:
var redisClient = redis.createClient();

var storeMessage = function(name,data){
  var message = JSON.stringify({name: name, data: data});
  redisClient.lpush("message",message,function(err,response){
    redisClient.ltrim("messages",0,9);
  });
}
and the join listener:
client.on('join',function(name)
  redisClient.lrange("messages,0,-1,function(err,messages){
    messages = messages.reverse();
    messages.forEach(function(message) {
      message = JSON.parse(message); 
      client.emit("messages",message.name+ ": " + message.data);
    });
  });
});

No comments:

Post a Comment