Service: Channel Listeners and Channels

There are three categories of channel objects: channels, channel listeners and channel factories. Channels are the interface between the application and the channel stack. Channel listeners are responsible for creating channels on the receive (or listen) side, typically in response to a new incoming message or connection. Channel factories are responsible for creating channels on the send side to initiate communication with an endpoint.

Channel Listeners and Channels

Channel listeners are responsible for creating channels and receiving messages from the layer below or from the network. Received messages are delivered to the layer above using a channel that is created by the channel listener.

The following diagram illustrates the process of receiving messages and delivering them to the layer above.

Channel listeners and channels
A channel listener receiving messages and delivering to the layer above through channels.

The process can be conceptually modeled as a queue inside each channel although the implementation may not actually use a queue. The channel listener is responsible for receiving messages from the layer below or the network and putting them in the queue. The channel is responsible for getting messages from the queue and handing them to the layer above when that layer asks for a message, for example by calling Receive on the channel.

WCF provides base class helpers for this process. (For a diagram of the channel helper classes discussed in this topic, see Channel Model Overview.)

The following discussion is based upon the Transport: UDP sample.

Creating a Channel Listener

The`UdpChannelListener that the sample implements derives from the <xref:System.ServiceModel.Channels.ChannelListenerBase> class. It uses a single UDP socket to receive datagrams. TheOnOpen` method receives data using the UDP socket in an asynchronous loop. The data are then converted into messages using the message encoding system:

message = UdpConstants.MessageEncoder.ReadMessage(  
  new ArraySegment<byte>(buffer, 0, count),   

Because the same datagram channel represents messages that arrive from a number of sources, the UdpChannelListener is a singleton listener. There is at most one active IChannel``associated with this listener at a time. The sample generates another one only if a channel that is returned by the AcceptChannel method is subsequently disposed. When a message is received, it is enqueued into this singleton channel.


The UdpInputChannel class implements IInputChannel. It consists of a queue of incoming messages that is populated by the UdpChannelListener's socket. These messages are dequeued by the Receive method.