Duplex Communication in Windows Communication Foundation

Servers and clients are the two most important entities as far as services are concerned. Between the server and the 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, the client requests data from the server and the server responds with the proper set of data that the client has requested. This type of communication is initiated by the client.

WCF-1.jpg

Simplex

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

WCF-2.jpg

Duplex

In this, either the client or the server can initiate the communication. When the latter receives the data, it responds back by sending an acknowledgement to the former.

WCF-3.jpg

The Service Part

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

WCF-4.jpg

Once the project is ready, remove the IService.cs and Service.svc files from the Solution Explorer. We do this because by default the generated files have a lot of code written in them, which does nothing but confuse. Now add  new WCF service .svc file; you can name it anything, I named mine 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 code above 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() that takes nothing and returns nothing, also the mode of communication for the function is one-way, 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 is only required 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, BroadcastMessage. That also takes one argument and is also one-way. Let's write some more code before explaining the entire concept.

It is now time to have some code written in our svc file. So, open the WebDuplex.svc.cs file, that should have a class named WebDuplex and that class should have the IWebDuplex interface implemented. 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>();

        }

    }

}


Whenever data transfer happens, it happens through a channel. A channel is basically a physical medium, a sort of path, that helps in transferring the binary information from one place to another. The client, while interacting with the server, uses this channel. When multiple clients interact, each client uses separate channels. In the preceding case we are using a similar process. We will call the function DoWork() from the client. Once the service is known, a call to the function is made by a client, it tracks the channel, it maitains the channel information so that it could return the data back if the 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 maintain the channel from the point where the client first made it's interaction with the service, until the client's dead. So, once the client calls DoWork(), we start sending the data back to client via the same channel, by calling the Broadcast function defined in the callback interface.

Finallyt we want to create the endpoint of our service, that should support duplexing. For the binding we will therefore use wsDualHttpBinding. In the web.config file, in the servicemodel tag, just add these six lines that 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 to the the next part.

The Client Part

In the Solution Explorer, add one more project, the console application, DuplexClient. Add a service reference to the service the we have just created, name it 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() that creates the instance of the instancecontext of the current client at first. Then pass that instance to the service when the client is created. With the instance context, from the client you can indicate information about your instance to the service. In the case of duplexing, it will host your callback object such that the service can access the OperationContext.Current.GetCallbackChannel<IMyContract>() to obtain the instance of your callback object.

There is a function Called Broadcast() that will be invoked when the service sends data to the client.

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

WCF-5.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all