Channels in WCF

Discussion in 'ASP.NET' started by MinalS, Dec 6, 2014.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    32
    Trophy Points:
    0
    The channels are used for transport, message interception and protocols. They are layered and a channel stack is created. The layered stack is used is a communication stack used for processing the messages. The channel stack is used for convert messages into a format which is compatible with the sender and the receiver for transport.

    In WCF, two channels are used for communication. They are transport and protocol channels. The transport channels are at the lower end of the channel stack. They are responsible for message transport. They protocols used by the transport channel are HTTP, TCP, MSMQ, peer to peer, and named pipes. The protocol channels are used for transforming and modifying messages. They are also known as layered channels. Several protocol channels are provided by WCF.

    The client and server need a channel stack for communication to be performed. The stack must be compatible with others. The bindings are used for the simplification in the creation of the channel stack. The bindings are created from the collection of the binding elements.

    The channel stack diagram to demonstrate the flow of the WCF client application from client side to the server side is as shown below.

    [​IMG]

    The message flows from the WCF client application through the client side channel stack through a transport to the server. The server channel stack listens to the messages and dispatched the messages to the server application.

    A channel stack contains series of channels configured through the binding elements. A binding contains series of binding elements. The top part contains the protocol channels. They are used for interacting with the messages; maintain security, reliable messaging, logging and transaction.

    The transport channels are used for sending the bytes over the TCP or HTTP protocols. They contain an encoder for converting the messages into an array of bytes for transport. The messages are converted from the XML format into an array through the encoder.

    Channel Shapes



    WCF supports three types of messages exchange patterns. They are one way, duplex and request – reply. To use these exchange patterns, WCF provides interfaces known as channel shapes. The shapes that can be used are IOutputChannel, IInputChannel, IDuplexChannel, IRequestChannel and IReplyChannel. Every channel contains a supportive sessions. The sessions are IOutputSessionChannel, IInputSessionChannel, IDuplexSessionChannel, IRequestSessionChannel and IReplySessionChannel.

    One – Way Communication Pattern

    In a one way communication, the messages travel in only one direction. They navigate from client to the server. The sender does not need to response back to the client. The acknowledgment is sent back to the client. The communication ends after the message is received. The IOutputChannel and IInputChannel are used for sending and receiving messages.

    The following diagram is used for demonstrating the one way communication pattern.

    [​IMG]

    The following code demonstrates the client application using the IOutputChannel channel for sending a message.

    Code:
    using System;
    using System.Collection.Generic;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Text;
    
    namespace InfoWCF
    {
        class Program
        {
            static void Main ( string[] args )
            {
                BasicHttpBinding bin1 = new BasicHttpBinding();
                BindingParameterCollection para1 = new BindingParameterCollection ();
                Message m = Message.CreateMessage( MessageVersion.Soap11, “urn:message” );
                IChannelFactory<IOutputChannel> factory = bin1.BuildChannelFactory<IOutputChannel>(parameters);
                IOutputChannel channel = factory.CreateChannel ( new EndPointAddress(“http://localhost/sendmessage/” ));
                channel.Send (m);
                channel.Close();
                factory.Close();
            }
        }
    }
    
    
    Duplex Communication

    In Duplex communication, the messages can be sent from the client or the server. The IDuplexChannel interface is used for the communication. The following diagram shows the duplex communication.

    [​IMG]

    An example of communication is coded below. The client provides an endpoint to send and receive messages to the server.

    Code:
    using System;
    using System.Collection.Generic;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Text;
    
    namespace InfoWCF
    {
        class Program
        {
            static void Main ( string[] args )
            {
                NetTcpBinding bin1 = new NetTcpBinding();
                BindingParameterCollection para1 = new BindingParameterCollection ();
                Message m = Message.CreateMessage( MessageVersion.Soap12WsAddressing, “urn:sendmessage” );
                IChannelFactory<IDuplexChannel> factory = bin1.BuildChannelFactory<IDuplexChannel>(parameters);
                IDuplexChannel channel = factory.CreateChannel ( new EndPointAddress(“net.tcp://localhost/sendmessage/” ));
                channel.Send (m);
                channel.Close();
                factory.Close();
            }
        }
    }
    
    Request Reply communication

    The reply request communication is a special way form of the two way communication. It contains only one reply for each request and is initiated by the client. Once the client sends the request it has to wait for the server response.

    The HTTP request demonstrates the use of the request reply communication. The browser initiates an HTTP request to the server, the server processes the requests and the reply is sent back. The IRequestChannel and IReplyChannel interfaces are used.

    The following figure demonstrates the request reply communication.

    [​IMG]

    The client application code using the IRequestChannel for sending the message is shown below.

    Code:
    
    using System;
    using System.Collection.Generic;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Text;
    
    namespace InfoWCF
    {
        class Program
        {
            static void Main ( string[] args )
            {
                BasicHttpBinding bin1 = new BasicHttpBinding();
                BindingParameterCollection para1 = new BindingParameterCollection ();
                Message request = Message.CreateMessage( MessageVersion.Soap11, “urn:sendmessage” );
                IChannelFactory<IRequestChannel> factory = bin1.BuildChannelFactory<IRequestChannel>(parameters);
                IRequestChannel channel = factory.CreateChannel ( new EndPointAddress(“http://localhost/sendmessage/” ));
                Message response = channel.Request(request);
                channel.Close();
                factory.Close();
            }
        }
    }
    
    

    Channel Listeners



    Channel listeners are the server side communication in WCF. They are used for listening messages, channel stacks creation, reference to the stack top. They use the transport channel or the channel stack. The Service Host class is used for hosting the service.

    The following code shows the channel listener for receiving the messages.

    Code:
    using System;
    using System.Collection.Generic;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    
    namespace InfoWCF
    {
        class Program
        {
            static void Main ( string[] args )
            {
                BasicHttpBinding bin1 = new BasicHttpBinding( BasicHttpSecurityMode.None );
                Uri address = new Uri (“http://localhost/request” );
                BindingParameterCollection b1 = new BindingParameterCollection();
                IChannelListener<IReplyChannel> listener = new binding.BuildChannelListener<IReplyChannel>(address, b1);
                listener.Open();
                IReplyChannel channel = listener.AcceptChannel ();
                Channel.Open();
                Console.WriteLine ( “Service Started” );
                Console.WriteLine(“Wating…”);
                RequestContext request = channel.ReceiveRequest();
                Message m1 = request.RequestMessage;
                string value = message.GetBody<string>();
                Message replymessage = Message.CreateMessage ( message.Version, “http://localhost/reply” , value);
                request.Reply(replymessage);
                Console.WriteLine(“Service Stopped”);
                m1.Close();
                request.Close();
                channel.Close();
                listener.Close();
        
                Console.Read();
            }
        }
    }
    

    Channel Factories



    A channel factory is used for creating a channel for sending and channel ownership. Mostly the user does not use the channel factories directly. The class derived from the ClientBase<> generated from the svcutil.exe are used.

    The code to demonstrate the use of the channel factory to call the service is shown below.

    Code:
    using System;
    using System.ServiceModel;
    using System.Text;
    using System.Collections.Generic;
    using System.ServiceModel.Channels;
    
    namespace InfoWCF
    {
        class Program
        {
            static void Main ( string[] args )
            {
                BasicHttpBinding bin1 = new BasicHttpBinding( BasicHttpSecurityMode.None);
                IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>( new BindingParameterCollection());
                factory.Open();
                IRequestChannel channel = factory.CreateChannel( new EndpointAddress (“ http://localhost/request") );
                channel.Open();
                Message request1 = Message.CreateMessage ( MessageVersion.Soap11, “http://webtech.com/reply”, “It contains data” );
                Console.WriteLine(“Message Sending”);
                Message reply1 = channel.Request(request1);
                string value = reply1.GetBody<string>();
                Console.WriteLine(“Receiving Reply”);
                request1.Close();
                reply1.Close();
                channel.Close();
                factory.Close();
            
                Console.Read();
            }
        }
    }
    
    
    ChannelFactory<>

    There are two channel factory classes known as ChannelFactory and ChannelFactory<>. These classes are separate and perform different functionalities. The ChannelFactory<> class is useful when several clients are to be created.

    The following code demonstrates the ChannelFactory<> class for implementing the interface.

    Code:
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    
    namespace InfoWCF
    {
        class Program
        {
            static void Main ( string[] args)
            {
                try
                {
                    using ( ChannelFactory<IProductService> cf1 = new ChannelFactory<IProductService>())
                {
                    IProductService sr1 = cf1.CreateChannel();
                try
                {
                    double value = sr1.GetData(“msft”);
                }
                catch ( Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
                catch ( Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                Console.ReadLine();
            }
        }
    }
    
    
    ICommunicationObject

    The ICommunicationObject interface is the base of all the communication objects in WCF. The developers who want to create the custom channels needs to know the interface. The objects in the communication need to implement the state machine. The ICommunicationObject is used for implementing the state machine.

    The interface for the ICommunicationObject is as shown below.

    Code:
    
    public interface ICommunicationObject 
    {
        event EventHandler Closed;
        event EventHandler Closing;
        event EventHandler Faulted;
        event EventHandler Opened;
        event EventHandler Opening;
    
        void Abort();
        IAsyncResult BeginClose( AsyncCallback callback, object state );
        IAsyncResult BeginClose( TimeSpan timeout, AsyncCallback callback, object state);
        IAsyncResult BeginOpen ( AsyncCallback callback, object state );
        IAsyncResult BeginOpen ( TimeSpan timeout, AsyncCallback callback, object state );    
    void Close();
        void Close( TimeSpan timeout );
        void EndClose( IAsyncResult result );
        void EndOpen ( IAsyncResult result );
        void Open();
        void Open ( TimeSpan timeout );
        
        CommunicationState State { get; }
    }
    
    The states provided by the CommunicationState enumeration are shown below.
    Code:
    public enum CommunicationState
    {
        Created,
        Opening,
        Opened,
        Closing,
        Closed,
        Faulted
    }
    
    The CommunicationState enumeration shows the six states of communication objects. The first or the initial state is called as Created. It is the initial state of all the instantiated objects. The final state is the Closed state. The methods are called on the ICommunicationObject interface.

    The events supported by the ICommunicationObject are Opening, Opened, Closing, Closed and Faulted.

    The ICommunicationObject interface is used for casting the communication methods and events. The CommunicationObject is the abstract base class that provided the implementation of the ICommunicationObject interface.

    The following code shows the ICommunicationObject example.
    Code:
    using System;
    using System.Collection.Generic;
    using System.Net;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    
    namespace InfoWCF
    {
        class Program
        {
            static void Main ( string[] args )
            {
                string data=”MSFT”;
                double value;
                
                ProductServiceClient client = new ProductServiceClient ());
                ICommunicationObject comobj = (ICommunicationObject) client;
                comobj.Closed+=new EventHandler ( Closed );
                comobj.Faulted+=new EventHandler ( Faulted );
                value = client.GetValue ( data );
                Console.WriteLine (“ {0} {1}”, data, value); 
                Console.ReadLine();
            }
            
            static void Closed ( object sender, EventArgs e)
            {
            }
            static void Faulted( object sender, EventArgs e)
            {
            }
        }
    }
    
     
    Last edited by a moderator: Jan 21, 2017

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice