How to achieve Duplex Communication in WCF using Duplex Contract in C#
Most of us are aware of how to use WCF to call server side API from client, but there is also a way to call client side API's from the Server. This is possible with the use of Duplex contract in WCF. With the help of duplex contract we will be able to achieve duplex communication. In this post we will be seeing how to accomplish this with the help of an example.
How to Define Duplex Contract in WCF?
To define the capabilities of a service we define what is called as a Service Contract which is also used for creating the proxies at the client side. While defining the Service contract there is a parameter called CallbackContract which takes in a type of Interface which is used to define the client side API's.
Server Side Implementation
In the constructor of the service we are querying the OperationContext to get an instance of the call back contract instance.
Client Side Implementation
Once its added then in the client side we have defined the class StateCallBackHandler which implements the callback contract which is generated at the client side by referring the WCF Service.
In the Main method we have created the instance of InstanceContext and passed the instance of the Callback Handler as an argument.
Then we have to create an instance of the client passing the instance context and call the client side API GetData().
After executing the above code we will get the output as shown below:
The first line is the data returned from the server and the second line is printed from the client side after a delay of 10 seconds as the Timer interval at the server was set to 10 seconds.
One point to note here is the binding which should be used for the Duplex Contract WCF Service, normal basichttpBinding will not support Duplex Contract.
we have to use Dual variant of the binding protocol such as "wsDualHttpBinding" to support Duplex Contract.
Comments
Post a Comment