Saturday, August 10, 2013

Duplex communication in Windows Communication Foundation

Server and Client, the two most important entity as far as services are concerned. Between Server and Client, the flow of information takes place. There are many ways this communication can be done, some of them are as follows:

1. Request-Response
2. Simplex
3. Duplex

Let’s have a look to each of them one by one:

Request-Response

In this process of communication, client request server for data and server respond with the proper set of data that the client has requested. This type of communication is client initiated.
         

                                      

Simplex

This is potentially one way communication where either of the two, client or server, on receiving data, need not to respond back to the sender.

                                    image

Duplex

In this, either client or server can initiate the communication. When the later receive the data, it respond back by sending the acknowledgement to the former.

                                image

The Service Part

Here in this post, we will look at how we can setup the duplex communication in Windows Communication Foundation. To begin with, we create a new WCF Service application project.

SNAGHTML53707c18

Once the project is ready, remove the IService.cs and Service.svc file from the solution explorer. We do this because the by default generated files have lot of code written in them, which does nothing but confuse. Now add new WCF service .svc file you can name it anything, I have named mine as WebDuplex. Once done we are ready to go.
Open the IWebDuplex interface that is created with our service. Write the exact code in the interface as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
 
namespace DuplexingSimplified
{
     // NOTE: You can use the "Rename" command on the "Refactor" 
     //menu to change the interface name "IWebDuplex" in 
     //both code and config file together.
    [ServiceContract(CallbackContract = typeof(IWebDuplexCallBack))]
    public interface IWebDuplex
    {
        [OperationContract(IsOneWay = true)]
        void DoWork();
    }
 
    public interface IWebDuplexCallBack
    {
        [OperationContract(IsOneWay = true)]
        void Broadcast(string msg);
    }
}

Let’s now talk about what the above code actually means. The interface IWebDuplex is the normal interface like what we create when we write a normal WCF service. It has a function DoWork() which take nothing and returns nothing, also the mode of communication for the function is oneway, meaning it can only be called by the client and it will return nothing. The functions are defined one way in the case when the client only require to invoke the function call without waiting for it to return values. That is to say fire-and-forget.
Next we have another interface IWebDuplexCallBack defined just below. This interface will be used for the call back. In the first interface IWebDuplex, as you can see, in the servicecontract attribute we have set the callback contract as the interface IWebDuplexCallback. In this interface we have only one function that is BroadcastMessage. Which also take one argument and is also one way.  Let’s write some more code before discussing the entire concept.

Now time to have some code written in our svc file. So, open WebDuplex.svc.cs file, which should have a class named WebDuplex and that class should have implemented IWebDuplex interface. Here is the entire code of the class.


public class WebDuplex : IWebDuplex
{       
   public void DoWork()
   {
       for(int i=0;i<=10;i++)
       {
           Callback.Broadcast(i.ToString());
           Thread.Sleep(5000);
       }
   }
 
   IWebDuplexCallBack Callback
   {
       get
       {
           return OperationContext.Current.GetCallbackChannel<IWebDuplexCallBack>();
       }
   }
}

Data transfer whenever happens, it happens through a channel. A channel is basically a physical medium, a path sort of, which helps in transferring the binary information from one place to another. Client while interacting with server uses this channel. When multiple client interacts, each client uses different channels. In the above case we are making use of similar process. We are going to call the function DoWork() from the client. Once the service know, that there is a call to the function is made by a client, it tracks the channel, it keep the channel information so that it could return the data back if client demanded, through the same channel only. Because, for sure the service knows, that at the end of the channel, there is a client.
In duplex communication, we keep track of the channel from the point where the client first made it’s interaction with service, until the client’s dead. So, once the client calls DoWork(), we starts sending the data back to client via same channel, by calling the Broadcast function defined in the callback interface.

Lastly we want to create the endpoint of our service, which should support duplexing. The binding therefore we are going to use is wsDualHttpBinding. In the web.config file, inside servicemodel tag, just adding these six lines will do that for us.


<services>
  <service name="DuplexingSimplified.WebDuplex">
    <endpoint address="" binding="wsDualHttpBinding" bindingConfiguration=""
      contract="DuplexingSimplified.IWebDuplex" />
  </service>
</services>

Our service is complete and ready to be consumed, let’s now move the the next part.

The Client Part

In the solution explorer add one more project, the console application, DuplexClient. Add service reference to the service the we have just created, name it as DuplexService. Once done, in the Program.cs file, write exactly the following code.


class Program: IWebDuplexCallback
{
    static void Main(string[] args)
    {
        Program program = new Program();
        program.init();
        Console.ReadLine();
    }
 
    public async void init()
    {
        InstanceContext instanceContext = new InstanceContext(this);
 
        // Create a client
        WebDuplexClient client = new WebDuplexClient(instanceContext);
        await client.DoWorkAsync();
    }
 
    public void Broadcast(string msg)
    {
        Console.WriteLine(msg);
    }
}

This class implements the interface IWebDuplexCallback. The call is made to the function init() which create the instance of the instancecontext of the current client at first. Then pass that instance to the service when the client is created. With instance context, from the client you can indicate information about your instance to the service. In the case of duplexing, it is going to host your callback object such that the service can access OperationContext.Current.GetCallbackChannel<IMyContract>() to obtain the instance of your callback object.
There is a function Called Broadcast() which will invoke when the service sends data to the client.

Just run the application by setting both the project as the startup projects. If everything works fine, you will see a black window with numbers from 0-9.

SNAGHTML53fdb9b6
Hope you’d like it. In case of any query, feel free to contact me.

Happy Reading!!!

Share this post

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top