Showing posts with label RealTimeWeb. Show all posts
Showing posts with label RealTimeWeb. Show all posts

Sunday, April 22, 2012

Real Time Messaging On Web - Sample Using Socket.IO and Node.Js

Socket.io enables real time synchronization across browsers while using different underlying transport methods.It uses different transport mechanisms to support multiple platforms.To understand how it works we need to get some basic principles behind socket.io .First thing is it can use several transport mechanisms like xhr-polling,xhr-multipart,htmlfile,websocket,flashsocket, jsonp-polling.The client will decide what transport method to use .To start the connection it will do a basic http hanshake and then based on client it will decide the transport method. Then it will use a lite weight protocol to communicate.

I'm doing this example on node server on windows. If you are new to Node.js it's better if you go through my previous article Node.JS Sample Application On Windows. . Here I'm going to use socket.io on Node server.

First we need to install Socket.io on Node server. For that go to your project folder and use npm command npm install socket.io . It will install socket.io in to your folder as a node module.

Now you can see a folder has been(node_modules) created in your project folder.
Then we need to have our web page. Create the Index.html page and save it in the project folder ,
 
 
  
   
   
    

Welcome to socket.io .....


Next step to create the server app to serve the HTML page , Create the Server.js with following code and save it in the project folder.
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8012);// give a port not used by other apps

function handler(req, res) {

    fs.readFile('index.html',
  function (err, data) {
      console.log(err);
      if (err) {
          res.writeHead(500);
          return res.end('Error loading index.html');
      }

      res.writeHead(200);
      res.end(data);
  });
}


So now we have all required files in project folder,

Then we can run our server, Go to the folder from comman prompt and exacute command node server.js
Then we can use the browser to see our index.html page user the url http://localhost:8012/
Then the important part, integration of socket.io for real time communication, There are several reserved event for the socket.io server, 'connection' - initial connection from a client.
'message' - "message" is emitted when a message sent with socket.send is received. function.
'disconnect'- fired when the socket disconnects.


For our sample app we can use the 'connection' event to send something on any connection , Append this code to the Server.js
io.sockets.on('connection', function (socket) {
    socket.emit('Initialdata', { hello: 'world' });
});


And then change your client (Index.html) to communicate with socket.io server with flowing code,





   

Welcome to socket.io .....


Then restart the node server (Again exacute node server.js command). Now you can see the alert by refreshing the web page,

So now we have up and running socket. Our next step is to make real time communicating clients. For that we need to add a text box and a button to the client and javascripts to send the message to the server to broadcast for other clients,
    
    


    

Welcome to socket.io .....

Now our client is ready for sending and receiving messages. Next step is to change the server to broadcast received message from any clients to all the other clients connected. Change the server with following code,
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8012);

function handler(req, res) {

    fs.readFile('index.html',
  function (err, data) {
      console.log(err);
      if (err) {
          res.writeHead(500);
          return res.end('Error loading index.html');
      }

      res.writeHead(200);
      res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
    console.log('Socket Created...');

    socket.emit('InitialData', { Message: 'Hello World !' });

    socket.on('sendMessage', function (data) {
        socket.broadcast.emit('messageRecieve', data);
    });
});

We are ready with our client and the server. Restart the server again using node server.js , and open two browser windows( http://localhost:8012/ ) to demonstrate multiple clients scenario ,