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 ,

Saturday, March 31, 2012

Node.JS Sample Application On Windows

I am I'm kind of new to  Node.js   world. I took nearly a week reading tutorials and downloading samples to say "Hello World" to Node.Js and to Socket.io. Finally today I have achieved it :). Let me document what I have done here before I forget all the things. Here I'm going to describe the first step running first Node server on windows. I will go through step by step starting from the downloading  Node.js .

Download and Install Node.js
We can download Node.JS server for windows from here . Nothing to configure... Just download and install it. You can check whether you have installed it correctly using command prompt. Type node and press Enter you will get the node prompt.

Host the sample script
This is the sample code for  hello world server.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Create new text file and save above code as sample.js

Run Sample Server
Then go to your folder (using command prompt) which has the sample.js file and execute it using node by executing command node sample.js


Access It Using Browser
Open your browser and enter the address we have given in the sample.js file.

That's It !
I will go more detail in to node.js and socket.io in the next post :).

Monday, March 26, 2012

Workflow Foundation 4 State Machine as a WCF Service

State machine workflow which we had in WF3.5 was not supported in WF4 (in .Net Framework4). But it released with .net framework 4 platform update 1 . State machine is very helpful to model long running workflows with higher external interactions. As an example in a long running order processing system where it needs several user inputs and approvals from external users.
There are several examples state machines in MSDN which describe the state machine well. But here I'm going to expose the state machine as a service. My example is a simple order processing system which has some human interaction to approve orders.

In this workflow there are three states(OrderRecived, To be Approved , Finished) and three triggers (Pay,IssueWithOrder,Resolve). We can create new order by giving an orderId and some amount.Then to complete the order we can pay using Pay trigger. Or else if there any issues with the order we can use another WCF call to workflow to change the state(to restrict pay) using IssueWithOrder trigger. The Resolve trigger is used to resolve the issues when they have any issues.

Download Sample Code



To expose the triggers as services what we need to do is to use send receive activities in triggers.
And the other important thing is correlation handling. Because when we need to call a already instantiated workflow instance we should have some identity to call the correct workflow instance. So in my example the correlation handler is the orderId. Because it is unique for an order which is unique for a workflow instance. So I have a state machine level correlation handler which uses the order id to correlate and each and every WCF call the workflow instance will use that variable as the correlation handler.
You can download my sample code here.