"Collection to" WCF Post series (9): Depth channel programming model Part 2-instance

Source: Internet
Author: User

Introduction

In essence, WCF is a Communications service framework that allows us to use different transport protocols to interact with different WS-* Series specifications using different message encoding forms, all of which are handled by the channel stack. In the WCF feature series (8): Deep channel programming model Part 1-design article, there is an in-depth understanding of the channel model in WCF, and in this article I will illustrate how the server receives the message in the channel model, and how the client sends the message.

Service-Side Channel

Instead of using the WCF programming model to communicate directly with the channel model, this article will help us further deepen our understanding of server-side processing messages, and we need to create bindings in the first step of listening and receiving messages on the server, either by using the built-in bindings in WCF or by using custom bindings, as shown in the following code , create a custombinding:

Create a custom binding       httptransportbindingelement ();  CustomBinding (bindingelements); 

HttpTransportBindingElement is added here, so the generated channel stack has an HTTP transport channel, and a text message encoder is also used. Next Call the CustomBinding Buildchannellistener method you just created to construct the channel listener, you need to specify the listening base address and binding parameters, and also call the open () method to open the channel listener, I believe you must remember the open () The method is defined in interface Icommunicationobject, as shown in the following code:

Create a channel listener         ichannellistener<ireplychannel> listener = binding using a custom binding      . buildchannellistener<ireplychannel> (         Uri (bindingparametercollection ());  Listens for message listener. Open (); Console.WriteLine ("Listening for incoming channel connections");       

Now listen for incoming messages, because we use the Request Response message exchange pattern, where the listener returns a channel that implements the IReplyChannel, in order to receive messages on this channel, we first call open () Method (The method is still defined in icommunicationobject) so that it can be placed in a state that is ready for communication. We then call the Receiverequest () method, which is blocked until the message is reached, as shown in the following code:

Create reply channels IReplyChannel channel = listener. Acceptchannel (); Console.WriteLine ("Channel accepted. Listening for Messages "); channel. Open (); RequestContext request = Channel. Receiverequest ();   

When the Receiverequest () method returns a RequestContext, it uses its Requestmessage property to get the received message. The operation (action) and content of the output message. In order to send a reply, a new reply message is created in this example, which takes the string data we received in the request, adds a character and then passes it back. Then, call the reply () method to send a reply message, as shown in the following code:

//read the requested message message message = Request. Requestmessage; console.writeline (console.writeline (string BODY = message. Getbody<string> (); message replymessage = message.createmessage ( Binding. MessageVersion,  "Http://www.cnblogs.com/TerryLee/Encode",  "Hello:" + body); request. Reply (replymessage);               

Finally, do not forget to do the resource release work, close the channel listener, channel, request message, request context, and so on, as shown in the following code:

Releases the object message. Close (); request. Close (); channel. Close (); listener. Close ();

The complete code is as follows:

<summary>///Author:terrylee///Url:http://www.cnblogs.com/terrylee</summary>static void Main () {To create a custom bindingbindingelement[] BindingElements =NewBINDINGELEMENT[2]; Bindingelements[0] =NewTextmessageencodingbindingelement (); BINDINGELEMENTS[1] =NewHttpTransportBindingElement ();CustomBinding binding =NewCustomBinding (bindingelements);Create a channel listener with a custom bindingichannellistener<Ireplychannel> listener = binding. buildchannellistener<Ireplychannel> (NewUri ("Http://localhost:8887/StringService"),NewBindingParameterCollection ());Listens for message listener. Open ();Console.WriteLine ("Listening for incoming channel connections");Create a reply channelIReplyChannel channel = listener. Acceptchannel ();Console.WriteLine ("Channel accepted. Listening for Messages "); Channel. Open ();RequestContext request = Channel. Receiverequest ();Read the requested messageMessage message = Request. Requestmessage;Console.WriteLine ("Message Received");Console.WriteLine (string BODY = message. Getbody<string> (); console.writeline (//Send Response message message replymessage = message.createmessage (Binding. MessageVersion,  "Http://www.cnblogs.com/TerryLee/Encode",  "Hello:" + body); Request. Reply (Replymessage); //releases object message. Close (); Request. Close (); Channel. Close (); Listener. Close (); console.writeline (console.readline ();}              

Now running server Side 1 shows that the Receiverequest () method will block because no message arrives:

Figure 1

Client Channel

Before we finish working on the service side, we'll look at how to communicate directly with the channel model on the client side. Consistent with the server, the first step in requesting a message is to create a binding, because both parties need to agree on the details of the communication through binding. Creating a custom binding is consistent with the service side, as shown in the following code:

Create a binding       httptransportbindingelement ();  CustomBinding (bindingelements); 

Next we need to construct the channel factory using the binding you just created, which we mentioned in the previous article that the receiver of the message uses the channel listener, and the message requester uses the channel factory, this time using the BuildChannelFactory () method to construct the channel factory and open it, as shown in the following code:

Use bindings to create a channel factory ichannelfactory<irequestchannel> factory =binding. buildchannelfactory<irequestchannel> (                 bindingparametercollection ());  Open the Channel Factory factory. Open (); Console.WriteLine ("Channel Factory opened");      

Now use the CreateChannel () method of the channel factory to create the IRequestChannel, and after the channel is obtained, call its open () method so that it is in a communication-ready state, as shown in the following code:

Create the request Channel IRequestChannel channel = Factory. CreateChannel (   endpointaddress ("Http://localhost:8887/StringService")); Open (); Console.WriteLine ("Request Channel opened");    

After you open the channel, you can create a message and use the channel's request () method to send the requests and wait for the response, where we send the message content "Terrylee", when this method returns, we will be able to get a reply message, can read the message to discover the endpoint reply content, as shown in the following code:

//Create request message message requestmessage = Span style= "color: #2b91af;" >message.createmessage (binding. MessageVersion,  "Terrylee"); //sends a request message and receives a response message message replymessage = Channel. Request (Requestmessage); console.writeline (console.writeline (string data = replymessage. Getbody<string> ();  "Reply content: {0}", data);       

Finally, the resource release is still working, close the channel factory, channel, and request message, as shown in the following code:

Replymessage. Close (); channel. Close (); factory. Close ();

The complete client code is:

<summary>///Author:terrylee///Url:http://www.cnblogs.com/terrylee</summary>public static void Main () {Create bindingsbindingelement[] BindingElements =NewBINDINGELEMENT[2]; Bindingelements[0] =NewTextmessageencodingbindingelement (); BINDINGELEMENTS[1] =NewHttpTransportBindingElement ();CustomBinding binding =NewCustomBinding (bindingelements);Creating a channel factory with bindingsichannelfactory<Irequestchannel> factory = binding. buildchannelfactory<Irequestchannel> (NewBindingParameterCollection ());Open the Channel Factory factory. Open ();Console.WriteLine ("Channel factory opened");Create a request ChannelIRequestChannel channel = Factory. CreateChannel (NewEndpointAddress ("Http://localhost:8887/StringService")); Channel. Open ();Console.WriteLine ("Request Channel opened");Create a request messageMessage Requestmessage =Message.createmessage (binding. MessageVersion,"Http://www.cnblogs.com/TerryLee/Encode","Terrylee"); //Send request message and receive response message Replymessage = Channel. Request (Requestmessage); Console.WriteLine ("Reply message received"); Console.WriteLine ("Reply action: {0}", Replymessage. Headers.action); string data = Replymessage. getbody<string> (); Console.WriteLine ("Reply content: {0}", data); Replymessage. Close (); Channel. Close (); Factory. Close (); Console.WriteLine ("Press Enter to exit"); console.readline ();}             

The last runtime is shown in server 2:

Figure 2

Client 3 shows the following:

Figure 3

Restudying

Now let's review the knowledge in the previous article that the channel object model is a set of core interfaces necessary to implement a channel, channel listener, and channel factory. Some base classes are also available to assist with custom implementations. You can see that the most important of the channel models are three sets of interfaces: Channel, channel Listener, and channel factory. Each channel implements one or more interfaces, called Channel shape interfaces or channel shapes, and the channel listener is responsible for listening for incoming messages, that is, at the receiving end of the message, and then passing the messages to the upper layer through a channel created by the channel listener, which is responsible for creating the channel for sending messages, that is, in the sender of the message, And when the channel factory shuts down, all channels created by the channel factory are closed. 4 is shown below:

Figure 4

In contrast to the sample code in this article, I believe you can have a deeper understanding of Figure 4.

Summarize

In this paper, we introduce a simple example of how the service side receives the message in the channel model and how the client sends the message, in the hope of helping everyone.

"Collection to" WCF Post series (9): Depth channel programming model Part 2-instance

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.