WCF learning tour-HTTP duplex mode (20), wcf duplex

Source: Internet
Author: User
Tags call back

WCF learning tour-HTTP duplex mode (20), wcf duplex
WCF learning tour-request and Reply Modes and one-way mode (19th)

 

Iv. HTTP duplex mode

 The duplex mode is based on the two modes implemented above to achieve mutual calls between the client and the server: the two methods described above are only the methods for the client to call the server, then, the server returns a return value to the client. Mutual call means that the client calls the method of the server, and the server can also call the method of the client.

Message Exchange based on duplex MEP (information Exchange mode, Message Exchange Pattern, the same below) can be considered as a combination of Message Exchange in multiple basic modes (such as request-reply mode and single mode. Duplex MEP has some variants. For example, a typical subscription-publishing mode can be seen as a manifestation of duplex mode.

1) two typical duplex MEP

1. Callback during request process

This is a typical form of Duplex message exchange mode. When a client calls a service, it attaches a callback object. The service is processing this, call back the client operation (this operation is executed on the client) through the callback object appended to the client (actually the proxy object that calls the callback service ). The entire message exchange process is actually composed of two basic message exchanges. One is the normal service request of the client, and the other is the callback of the server to the client. The two can adopt the request-reply mode, or One-way MEP for message exchange.Figure 1Describes this process. Both service calls and callbacks adopt request-reply.


Figure 1 callback in the Request Process

2. Subscription-publish

Subscription-publish mode is a typical variant of duplex mode. In this mode, both parties of the message exchange become subscribers and publishers. Several subscribers apply to the publisher for a topic, and the publisher saves all subscribers in a subscriber list, send a topic to all subscribers of the topic at a certain time. In fact, the message exchange based on the subscription-publish mode can also be seen as a combination of message exchange in two basic modes. The application subscription mode is a one-way message exchange mode (if the subscriber behavior gets feedback from the subscription, the message exchange mode can also be used). Topic publishing is also a one-way message exchange process. The subscription-publish message exchange mode is shown in figureFigure 2.

 

 

Figure 2 Subscription-publish

Ii) Example demonstration: Create a duplex communication-based WCF Application

Next, we will use an instance to learn the WCF Application Based on duplex communication. For the sake of simplicity, we will continue with the above (WCF Study Tour-request and reply mode and one-way mode (19th) examples. In the above example, we call BookService to directly display the book name and output the result through the Winform application. In this example, we will use another completely different method to call the service and output the result: One-way) call BookService (that is, the client cannot obtain the result by replying to the message). After the book name is displayed, the server displays the book name on the client by calling back.

Step 1: Define the service contract and callback contract

First, define the service contract. We define the service contract through the interface (IBookService) as follows, and act on the DisplayName operation of the specified method for displaying the book name, we define an operation as a one-way operation through the IsOneway attribute of the OperationContractAttribute feature. This means that the client only sends a request to the server and does not receive any results by replying to the message.

Using System; using System. collections. generic; using System. linq; using System. runtime. serialization; using System. serviceModel; using System. text; namespace WcfServiceLib {// Note: You can use the "RENAME" command on the "refactor" menu to change the Interface Name "IBookService" in the Code and configuration file at the same time ". [ServiceContract (CallbackContract = typeof (ICallback)] public interface IBookService {// <summary> // ticket mode, display name // </summary> /// <param name = "name"> book name </param> [OperationContract (IsOneWay = true)] void DisplayName (string name );}}

 

The function we want to implement is to achieve the result output by calling back the client on the server. The client normally calls the BookService service method. In the Service Execution Process, the client calls back the client's operations by using the callback object provided by the client during service calling, in essence, it is another form of service calling. WCF uses a service contract-based call. A normal service call on the client requires a service contract. Similarly, the server callback client still needs to describe the service contract for the callback operation, we call this service contract a callback contract. The type of the callback contract is specified by the CallbackContract attribute of ServiceContractAttribute.

In the code above, the callback contract ICallback of the service contract IBookService is defined as follows. Since the callback contract is essentially a service contract, the definition method is basically the same as that in the general sense. The difference is that, because the [ServiceContract (CallbackContract = typeof (ICallback)] indicates that ICallback is a service contract when IBookService is defined, the ServiceContractAttribute feature is no longer required for ICallback. ICallback defines a service operation DisplayResult to display the book name and date. Because the server does not need to return a callback value, the callback operation is also set as a one-way method. The ICallback interface code is as follows.

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.Text; namespace WcfServiceLib{    public interface ICallback    {        [OperationContract(IsOneWay = true)]        void DisplayResult(string result);    }}

 

Step 2: implement services

BookService implements the methods in the service contract IBookService defined above, implements the DisplayName operation, and displays the book name and date. At the same time, the book name and date are displayed on the client through callback, so you need to use the callback object provided by the client (this object is specified when the client calls BookService, ). In WCF, the callback object is obtained through the GetCallback <T> method of the current OperationContext (T indicates the type of the callback contract ). The Code is as follows.

 

Using System; using System. collections. generic; using System. linq; using System. runtime. serialization; using System. serviceModel; using System. text; namespace WcfServiceLib {// Note: use the "RENAME" command on the "refactor" menu to change the class name "BookService" in the code, svc, and configuration file at the same time ". // Note: To start the WCF test client to test the service, select BookService. svc or BookService. svc. cs in Solution Explorer and start debugging. Public class BookService: IBookService {// <summary> // duplex mode, callback display result /// </summary> /// <param name = "name"> name </param> public void DisplayName (string name) {string result = string. format ("book name: {0}, date and time {1}", name, DateTime. now. toString ("yyyy-MM-dd HH: mm: ss"); Console. writeLine ("\ r \ n" + result); ICallback call = OperationContext. current. getCallbackChannel <ICallback> (); call. displayResult ("Callback ---" + result );}}}

 

Note: OperationContext is a very important and useful object in WCF. It represents the context of service operation execution. We can obtain the Current OperationContext through the static attribute Current (OperationContext. Current. With OperationContext, we can obtain or set some contexts on the server or client. For example, on the client, we can add SOAP Headers and HTTP headers (such as cookies) to the outgoing message). On the server side, you can use OperationContex to obtain the SOAP header and HTTP header set on the client. For more information about OperationContext, see the MSDN online documentation.

Step 3: Service boarding

We use a console application to host the BookService and define all the parameters of the Service in the code. Because duplex communication relies on a duplex channel stack, that is, a binding that supports duplex communication, we chose WSDualHttpBinding.

Using System; using System. collections. generic; using System. linq; using System. serviceModel; using System. serviceModel. description; using System. text; using System. threading. tasks; using WcfServiceLib; namespace ConsoleHosting {class Program {static void Main (string [] args) {// create a host's base address Uri baseAddress = new Uri (" http://localhost:8080/BookService "); // Create the host using (ServiceHost host = new ServiceHost (typeof (BookService), baseAddress) {// Add the endpoint host to the host. addServiceEndpoint (typeof (IBookService), new WSDualHttpBinding (), baseAddress); if (host. description. behaviors. find <ServiceMetadataBehavior> () = null) {// set the HttpGetEnabled attribute to true ServiceMetadataBehavior behavior = new ServiceMetadataBehavior (); behavior. httpGetEnabled = true; behavior. httpG EtUrl = baseAddress; // Add behavior to Behaviors host. description. behaviors. add (behavior); // open the host. opened + = delegate {Console. writeLine ("The BookService console program host has been started, and the HTTP listener has been started ...., press any key to terminate the service! ") ;}; Host. open (); // print endpoint information Console. foregroundColor = ConsoleColor. yellow; foreach (ServiceEndpoint se in host. description. endpoints) {Console. writeLine ("[endpoint]: {0} \ r \ n \ t [A-address]: {1} \ r \ n \ t [B-binding]: {2} \ r \ n \ t [C-Protocol]: {3} ", se. name, se. address, se. binding. name, se. contract. name);} Console. read ();}}}}}

Note:In the predefined WCF binding type, both WSDualHttpBinding and NetTcpBinding provide support for duplex communication, but the two have essential differences in the implementation mechanism of duplex communication. WSDualHttpBinding is based on the HTTP transmission protocol, while the HTTP protocol itself is based on the request-reply transmission protocol, and the HTTP-based channel is essentially one-way. WSDualHttpBinding actually creates two channels, one for communications between the client and the server, and the other for communications between the server and the client, indirectly providing duplex communication. NetTcpBinding is fully based on TCP protocol that supports duplex communication.

 

Step 4: implement the callback contract

The client program provides implementation for the callback contract. In the following code, BookCallBack implements the callback contract ICallback, and outputs the display of the book name and date in the DisplayResult method.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace WinClient {class BookCallBack: BookServiceReference. IBookServiceCallback {// declare a delegate (delegate) type: delegateDispalyResult. the return value of this type can be null, and the parameter has only one (string type) method. Public delegate void delegateDispalyResult (string result); // declare an object of the delegateDispalyResult type. This object indicates that the returned value is null and the parameter has only one (string type) method. It can carry N methods. Public delegateDispalyResult mainThread; public void DisplayResult (string result) {mainThread (result); // use the delegate method to display the book name and date information in the main interface Console. writeLine (result );}}}

 

Step 5: Call the service

The next step is to call a duplex service. This is a Web service reference that adds the corresponding WCF Service call object (for how to add a Web service reference, refer to the previous article ). In the service calling program, create a callback object, encapsulate the callback object through InstanceContext, and pass the InstanceContext object as a parameter to the service calling object.

 

Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. serviceModel; using System. text; using System. threading. tasks; using System. windows. forms; namespace WinClient {public partial class Form1: Form {BookCallBack call; public Form1 () {InitializeComponent (); // create a BookCallBack class Object BookCallBack call = new BookCall Back (); call. mainThread + = new BookCallBack. delegateDispalyResult (DisplayResult); instanceContext = new InstanceContext (call);} InstanceContext instanceContext; private void buttonTwoWay_Click (object sender, EventArgs e) {BookServiceReference. bookServiceClient client = new BookServiceReference. bookServiceClient (instanceContext); // carry two methods on the mainThread (delegate) object of the BookCallBack object. When the mainThread object is called in the thread These two methods. TextBox1.Text + = string. format ("start calling the wcf Service: {0} \ r \ n", DateTime. now. toString ("yyyy-MM-dd HH: mm: ss"); client. displayName ("science can read books in this way"); textBox1.Text + = string. format ("\ r \ n call end: {0}", DateTime. now. toString ("yyyy-MM-dd HH: mm: ss "));} /// <summary> /// display the callback result on the Interface /// </summary> /// <param name = "result"> </param> private void DisplayResult (string result) {// determine whether the method is called by the main thread, that is, the thread that creates the labMessage1 control. When the InvokeRequired attribute is true, it indicates that it is called by a thread other than the main thread. If no judgment is added, an exception occurs if (this. textBox1.InvokeRequired) {// create a new BookCallBack class object call = new BookCallBack (); // call the method for carrying the mainThread object of the new object. mainThread + = new BookCallBack. delegateDispalyResult (DisplayResult); // this indicates the form, where the Invoke method of the form is called, that is, the method for executing mainThread object delegation using the form creation thread, add the required parameter (I) this. invoke (call. mainThread, new object [] {result});} else {textBox1.Text + = "\ r \ n" + result ;}}}}

 

When the service host Program is enabled, after running the client program, the computation result executed by the server is displayed through the callback client operation. The following is the final output result.

Related Article

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.