A tentative approach to WCF -13:WCF client creates callback object for duplex service

Source: Internet
Author: User

Preface:

On WCF -5: Duplex Communication in WCF Message Exchange Mode (Duplex) in the blog post, I explained a scenario for the duplex Communication Service, the subscription and release model, which , I'll explain how a WCF client creates a callback object for a duplex service, using a message-sending example.

The duplex service specifies a callback contract that the client application must implement to provide a callback object that the service can invoke according to the contract requirements. Although the callback object is not a complete service (for example, you cannot start a channel with a callback object), these callback objects can be considered a service for implementation and configuration.

The client for the duplex service must:

    • Implements a callback contract class.
    • Creates an instance of the callback contract implementation class and uses the instance to create a System.ServiceModel.InstanceContext object that is passed to the WCF client constructor.
    • Invokes the operation and processes the operation callback.

The Duplex WCF client object has the same functionality as its non-duplex counterparts, in addition to the functionality required to support callbacks, including the configuration of the callback service.

Example Description:

    • The Service service contract defines a Send method send, using Isoneway=true, for the client to invoke and send a message to the server. The service also provides callback interface Imessageexchangecallback for duplex communication, which defines the method receive that sends a message to the client after the server receives the message, which is when the client sends the message to the server and the server invokes the callback method. Sends a message to the client.
    • The client needs to implement the class CallbackHandler of the duplex contract callback interface and implement the Receive method.
    • The WCF client generated for the duplex contract needs to provide a InstanceContext class at construction time. This InstanceContext class is used as the location of the object that implements the callback interface and handles messages sent back from the service. The InstanceContext class is constructed with an instance of the CallbackHandler class. This object handles messages sent from the service to the client through the callback interface.

  

WCF Example of a client creating a callback object for a duplex service:

    • The solution is as follows:

  

    • Engineering Structure Description:
    1. Service: A class Library program that defines a service contract interface and a callback interface to implement a services contract. The Send method is defined in Imessageexchange, and the Duplex service callback interface Imessageexchangecallback is also defined.

The code for IMessageExchange.cs is as follows:

usingSystem.ServiceModel;usingSystem.Collections.Generic;usingSystem.Runtime.Serialization;namespaceservice{[ServiceContract (SessionMode= sessionmode.required, CallbackContract =typeof(Imessageexchangecallback))]  Public InterfaceImessageexchange {[OperationContract (IsOneWay=true)]        voidSend (stringmessage); }     Public InterfaceImessageexchangecallback {[OperationContract (IsOneWay=true)]        voidReceive (stringmessage); }}                                                

The code for MessageExchange.cs is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.ServiceModel;namespaceservice{[ServiceBehavior (InstanceContextMode=instancecontextmode.persession)] Public classMessageexchange:imessageexchange { Public voidSend (stringmessage) {Console.WriteLine ("the server listens for messages sent by the client:"+message);        callback.receive (message); } imessageexchangecallback Callback {Get            {                returnOperationcontext.current.getcallbackchannel<imessageexchangecallback>(); }        }    }}

Note: Callback Contract interface Imessageexchangecallback in the Receive method is implemented at the client, so if a callback method needs to be invoked on the server, it must be obtained through the instance context of the current operation, i.e. the Callback object.

2. Host: Console Application. Provides a service-boarding program that adds a reference to the Srevice assembly. Complete the configuration file and code to host the service.

The code for Program.cs is as follows:

  
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingService;usingSystem.ServiceModel;namespacehost{classProgram {Static voidMain (string[] args) {            using(ServiceHost host =NewServiceHost (typeof(Messageexchange))) {host.} Opened+=Delegate{Console.WriteLine ("Service has been started, press any key to terminate! ");                }; Host.                Open ();            Console.read (); }        }    }}
View Code

The code for App. Config is as follows:

  
<?xml version="1.0"?><configuration> <system.serviceModel> <services> <service name="Service.messageexchange"behaviorconfiguration="Mexbehavior"> "http://localhost:1234/MessageExchange/"/> </baseAddresses> ""binding="wsdualhttpbinding"contract="Service.imessageexchange"/> <endpoint address="Mex"binding="mexhttpbinding"contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Mexbehavior"> <servicemetadata httpgetenabled="true"/> <servicedebug includeexceptiondetailinfaults="true"/> </behavior> </serviceBehaviors> </behaviors> &LT;/SYSTEM.S Ervicemodel></configuration>
View Code

3. Client: Console Application. Client program, after you start the service Host program host, add a reference to the service address http://localhost:1234/MessageExchange/, change the namespace to

Messageexchangeserviceref, then completes the implementation of the Duplex service callback interface Imessageexchangecallback and calls to the service method at Program.cs. The code for Program.cs is as follows:

usingSystem;usingClient.messageexchangeserviceref;usingSystem.ServiceModel;namespaceclient1{ Public classCallbackhandler:imessageexchangecallback { Public voidReceive (stringmessage) {Console.WriteLine ("the client listens for messages received by the server:"+message); }    }    classProgram {Static voidMain (string[] args) {InstanceContext InstanceContext=NewInstanceContext (NewCallbackHandler ()); Messageexchangeclient Proxy=Newmessageexchangeclient (InstanceContext); Proxy. Send ("WCF Duplex");        Console.read (); }    }}

The results of the operation are as follows:

  

Summarize:

    • This article simulates a client sending a message to the server, which, after receiving a message from the server, displays the message that is being heard on the client. Hopefully, with this example, there's a sense of progress in duplex communication, and I'll parse it later in the blog post for instance and session.

A tentative approach to WCF -13:WCF client creates callback object for duplex service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.