Partager via


WCF Extensibility – Channels (server side)

This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page.

Last week I introduced the channel model in WCF, with an emphasis on the channels at the client side. But that’s usually just half of the story - although the example I provided didn’t require a server-side channel counterpart, in many cases there are two channels, on the client and the server, acting together to provide some functionality to the WCF pipeline. This post will go into a little more detail on the server aspects of channels, especially how they’re created and inserted into the WCF stack.

Unlike on the client, where a channel factory is used for creating the channel instances, on the server side WCF uses channel listeners for that purpose. A factory basically sits there waiting for a call to be made (IChannelFactory<T>.CreateChannel) to return a channel, and a client channel sits idle until some channel (or the service model proxy) makes a call to send a message along (e.g., IRequestChannel.Request or IOutputChannel.Send). A channel listener, on the other hand, will actively try to “pump” channels from the listener sitting below it in the stack (the transport channel will sit listening for sockets or something similar from the network), in an “accept loop” similar to the one shown below.

  1. IChannelListener<IReplyChannel> listener = CreateListener();
  2. while (true)
  3. {
  4.     try
  5.     {
  6.         IReplyChannel channel = listener.AcceptChannel(TimeSpan.FromMinutes(5));
  7.         ProcessChannel(channel);
  8.     }
  9.     catch (TimeoutException)
  10.     {
  11.     }
  12. }

Basically, the listener will be asked to “accept” a channel for a certain time, and it should return it whenever one is available. If no channels are available after the timeout, the listener will throw. In many cases, the channel will be available right away – for example, the listener created by the HttpTransportBindingElement returns a “channel acceptor” class which waits for incoming connections in the HTTP port it’s listening to. The “server” channels will then follow a similar pumping pattern, this time waiting for incoming messages to arrive. Notice that this is similar to the way the HttpListener class is often used for for creating a generic HTTP server (although HttpListener has an event-based option which makes this a little easier; no such luck for WCF channels, unfortunately).

  1. while (true)
  2. {
  3.     try
  4.     {
  5.         RequestContext requestContext = channel.ReceiveRequest(TimeSpan.FromSeconds(10));
  6.         ProcessRequest(requestContext);
  7.     }
  8.     catch (TimeoutException)
  9.     {
  10.     }
  11. }

Notice that those snippets show the synchronous versions of the pump messages, but the WCF runtime by default uses their asynchronous versions (and for channels, the Try(Timeout, out result) pattern): IChannelListener<TChannel>.BeginAcceptChannel / IChannelListener<TChannel>.EndAcceptChannel for the listener, IReplyChannel.BeginTryReceiveRequest / IReplyChannel.EndTryReceiveRequest for reply channels (or IInputChannel.BeginTryReceive / IInputChannel.EndTryReceive for input channels). The calls to the channels can be changed to use the synchronous versions (TryReceiveRequest / TryReceive) by using the SynchronousReceiveBehavior endpoint behavior.

Request Context and messages

There are essentially two kinds of server channels as far as receiving messages: input channels and reply channels – duplex channels are just a pair of input / output channel, and session channels are the same as the non-session ones with an added identifier for the session for the communication. On input channels (used in datagram-like communication), the client simply sends a message and “forgets”, not waiting for a response. The input channel implements this behavior by simply returning the message directly to the caller on the Receive (or TryReceive, or Begin/EndReceive, or Begin/EndTryReceive). After the channel returns the message, it will go back to the pump loop waiting for a new one, and that message is “done”.

Reply channels, on the other hand, need to send a response to the message which it received, so instead of simply delivering the message to the caller, it will return a RequestContext object. The request context is the object which can be used to send the reply which is correlated to the incoming request. The request context has a property which holds a reference to the incoming request, and some methods to send a reply to the caller – it’s the responsibility of the code which called IReplyChannel.ReceiveRequest (or its variants) to call RequestContext.Reply (or BeginReply / EndReply) on the context to return a response to the caller. If this is not done in a timely manner, the channel will abort the request. The

How to add custom channels (server side)

Just like the client, it all starts at the binding. So one needs to write a binding element, and create a binding containing this element. The binding element class would override CanBuildChannelListener<TChannel> (to determine whether the channel shape is supported) and BuildChannelListener<TChannel> to actually return a channel listener which is capable of accepting the requested channel type. The channel listener implementation needs to override the AcceptChannel methods (or OnAcceptChannel and its asynchronous / try variants), if the class inherits from ChannelListenerBase<TChannel>), besides a lot of boilerplate methods (Open, BeginOpen, EndOpen, Close, etc.) to finally return the channel which will be used in the pipeline. To illustrate the verboseness of all of this, this is I think the simplest code to write a server channel that I can think of (it just passes the message along, and supports only IReplyChannel, although supporting IInputChannel wouldn’t add a lot more code).

  1. public class WrappingBindingElement : BindingElement
  2. {
  3.     public WrappingBindingElement()
  4.     {
  5.     }
  6.  
  7.     public override BindingElement Clone()
  8.     {
  9.         return new WrappingBindingElement();
  10.     }
  11.  
  12.     public override T GetProperty<T>(BindingContext context)
  13.     {
  14.         return context.GetInnerProperty<T>();
  15.     }
  16.  
  17.     public override bool CanBuildChannelListener<TChannel>(BindingContext context)
  18.     {
  19.         return typeof(TChannel) == typeof(IReplyChannel)
  20.             && context.CanBuildInnerChannelListener<TChannel>();
  21.     }
  22.  
  23.     public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
  24.     {
  25.         if (context == null)
  26.         {
  27.             throw new ArgumentNullException("context");
  28.         }
  29.  
  30.         if (typeof(TChannel) != typeof(IReplyChannel))
  31.         {
  32.             throw new InvalidOperationException("Only IReplyChannel is supported");
  33.         }
  34.  
  35.         var result = new WrappingListener(context.BuildInnerChannelListener<IReplyChannel>());
  36.         return (IChannelListener<TChannel>)result;
  37.     }
  38.  
  39.     class WrappingListener : ChannelListenerBase<IReplyChannel>
  40.     {
  41.         IChannelListener<IReplyChannel> innerListener;
  42.         public WrappingListener(IChannelListener<IReplyChannel> innerListener)
  43.         {
  44.             this.innerListener = innerListener;
  45.         }
  46.  
  47.         public override T GetProperty<T>()
  48.         {
  49.             T baseProperty = base.GetProperty<T>();
  50.             if (baseProperty != null)
  51.             {
  52.                 return baseProperty;
  53.             }
  54.  
  55.             return this.innerListener.GetProperty<T>();
  56.         }
  57.  
  58.         protected override IReplyChannel OnAcceptChannel(TimeSpan timeout)
  59.         {
  60.             return this.WrapChannel(this.innerListener.AcceptChannel(timeout));
  61.         }
  62.  
  63.         protected override IAsyncResult OnBeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state)
  64.         {
  65.             return this.innerListener.BeginAcceptChannel(timeout, callback, state);
  66.         }
  67.  
  68.         protected override IReplyChannel OnEndAcceptChannel(IAsyncResult result)
  69.         {
  70.             return this.WrapChannel(this.innerListener.EndAcceptChannel(result));
  71.         }
  72.  
  73.         protected override IAsyncResult OnBeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state)
  74.         {
  75.             return this.innerListener.BeginWaitForChannel(timeout, callback, state);
  76.         }
  77.  
  78.         protected override bool OnEndWaitForChannel(IAsyncResult result)
  79.         {
  80.             return this.innerListener.EndWaitForChannel(result);
  81.         }
  82.  
  83.         protected override bool OnWaitForChannel(TimeSpan timeout)
  84.         {
  85.             return this.innerListener.WaitForChannel(timeout);
  86.         }
  87.  
  88.         private IReplyChannel WrapChannel(IReplyChannel innerChannel)
  89.         {
  90.             if (innerChannel == null)
  91.             {
  92.                 return null;
  93.             }
  94.  
  95.             return new WrappingChannel(this, innerChannel);
  96.         }
  97.  
  98.         #region Other properties / methods which are delegated to the inner listener
  99.         public override Uri Uri
  100.         {
  101.             get { return this.innerListener.Uri; }
  102.         }
  103.  
  104.         protected override void OnAbort()
  105.         {
  106.             this.innerListener.Abort();
  107.         }
  108.  
  109.         protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
  110.         {
  111.             return this.innerListener.BeginClose(timeout, callback, state);
  112.         }
  113.  
  114.         protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
  115.         {
  116.             return this.innerListener.BeginOpen(timeout, callback, state);
  117.         }
  118.  
  119.         protected override void OnClose(TimeSpan timeout)
  120.         {
  121.             this.innerListener.Close(timeout);
  122.         }
  123.  
  124.         protected override void OnEndClose(IAsyncResult result)
  125.         {
  126.             this.innerListener.EndClose(result);
  127.         }
  128.  
  129.         protected override void OnEndOpen(IAsyncResult result)
  130.         {
  131.             this.innerListener.EndOpen(result);
  132.         }
  133.  
  134.         protected override void OnOpen(TimeSpan timeout)
  135.         {
  136.             this.innerListener.Open(timeout);
  137.         }
  138.         #endregion
  139.     }
  140.  
  141.     class WrappingChannel : ChannelBase, IReplyChannel
  142.     {
  143.         IReplyChannel innerChannel;
  144.         public WrappingChannel(ChannelManagerBase channelManager, IReplyChannel innerChannel)
  145.             : base(channelManager)
  146.         {
  147.             if (innerChannel == null)
  148.             {
  149.                 throw new ArgumentNullException("innerChannel");
  150.             }
  151.  
  152.             this.innerChannel = innerChannel;
  153.         }
  154.  
  155.         public IAsyncResult BeginReceiveRequest(TimeSpan timeout, AsyncCallback callback, object state)
  156.         {
  157.             return this.innerChannel.BeginReceiveRequest(timeout, callback, state);
  158.         }
  159.  
  160.         public IAsyncResult BeginReceiveRequest(AsyncCallback callback, object state)
  161.         {
  162.             return this.BeginReceiveRequest(this.DefaultReceiveTimeout, callback, state);
  163.         }
  164.  
  165.         public IAsyncResult BeginTryReceiveRequest(TimeSpan timeout, AsyncCallback callback, object state)
  166.         {
  167.             return this.innerChannel.BeginTryReceiveRequest(timeout, callback, state);
  168.         }
  169.  
  170.         public IAsyncResult BeginWaitForRequest(TimeSpan timeout, AsyncCallback callback, object state)
  171.         {
  172.             return this.innerChannel.BeginWaitForRequest(timeout, callback, state);
  173.         }
  174.  
  175.         public RequestContext EndReceiveRequest(IAsyncResult result)
  176.         {
  177.             return this.WrapContext(this.innerChannel.EndReceiveRequest(result));
  178.         }
  179.  
  180.         public bool EndTryReceiveRequest(IAsyncResult result, out RequestContext context)
  181.         {
  182.             bool endTryResult = this.innerChannel.EndTryReceiveRequest(result, out context);
  183.             if (endTryResult)
  184.             {
  185.                 context = this.WrapContext(context);
  186.             }
  187.  
  188.             return endTryResult;
  189.         }
  190.  
  191.         public bool EndWaitForRequest(IAsyncResult result)
  192.         {
  193.             return this.innerChannel.EndWaitForRequest(result);
  194.         }
  195.  
  196.         public RequestContext ReceiveRequest(TimeSpan timeout)
  197.         {
  198.             RequestContext context = this.innerChannel.ReceiveRequest(timeout);
  199.             return this.WrapContext(context);
  200.         }
  201.  
  202.         public RequestContext ReceiveRequest()
  203.         {
  204.             return this.ReceiveRequest(this.DefaultReceiveTimeout);
  205.         }
  206.  
  207.         public bool TryReceiveRequest(TimeSpan timeout, out RequestContext context)
  208.         {
  209.             bool result = this.innerChannel.TryReceiveRequest(timeout, out context);
  210.             if (result)
  211.             {
  212.                 context = this.WrapContext(context);
  213.             }
  214.  
  215.             return result;
  216.         }
  217.  
  218.         public bool WaitForRequest(TimeSpan timeout)
  219.         {
  220.             return this.innerChannel.WaitForRequest(timeout);
  221.         }
  222.  
  223.         private RequestContext WrapContext(RequestContext innerContext)
  224.         {
  225.             if (innerContext == null)
  226.             {
  227.                 return null;
  228.             }
  229.             else
  230.             {
  231.                 return new WrappingRequestContext(this, innerContext);
  232.             }
  233.         }
  234.  
  235.         #region Other properties / methods which are delegated to the inner channel
  236.         public override T GetProperty<T>()
  237.         {
  238.             return this.innerChannel.GetProperty<T>();
  239.         }
  240.  
  241.         protected override void OnAbort()
  242.         {
  243.             this.innerChannel.Abort();
  244.         }
  245.  
  246.         protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
  247.         {
  248.             return this.innerChannel.BeginClose(timeout, callback, state);
  249.         }
  250.  
  251.         protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
  252.         {
  253.             return this.innerChannel.BeginOpen(timeout, callback, state);
  254.         }
  255.  
  256.         protected override void OnClose(TimeSpan timeout)
  257.         {
  258.             this.innerChannel.Close(timeout);
  259.         }
  260.  
  261.         protected override void OnEndClose(IAsyncResult result)
  262.         {
  263.             this.innerChannel.EndClose(result);
  264.         }
  265.  
  266.         protected override void OnEndOpen(IAsyncResult result)
  267.         {
  268.             this.innerChannel.EndOpen(result);
  269.         }
  270.  
  271.         protected override void OnOpen(TimeSpan timeout)
  272.         {
  273.             this.innerChannel.Open(timeout);
  274.         }
  275.  
  276.         public EndpointAddress LocalAddress
  277.         {
  278.             get { return this.innerChannel.LocalAddress; }
  279.         }
  280.         #endregion
  281.  
  282.         class WrappingRequestContext : RequestContext
  283.         {
  284.             RequestContext innerContext;
  285.             WrappingChannel channel;
  286.             public WrappingRequestContext(WrappingChannel channel, RequestContext innerContext)
  287.             {
  288.                 this.innerContext = innerContext;
  289.                 this.channel = channel;
  290.             }
  291.  
  292.             public override void Abort()
  293.             {
  294.                 this.innerContext.Abort();
  295.             }
  296.  
  297.             public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state)
  298.             {
  299.                 return this.innerContext.BeginReply(message, timeout, callback, state);
  300.             }
  301.  
  302.             public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state)
  303.             {
  304.                 return this.BeginReply(message, this.channel.DefaultSendTimeout, callback, state);
  305.             }
  306.  
  307.             public override void Close(TimeSpan timeout)
  308.             {
  309.                 this.innerContext.Close(timeout);
  310.             }
  311.  
  312.             public override void Close()
  313.             {
  314.                 this.innerContext.Close();
  315.             }
  316.  
  317.             public override void EndReply(IAsyncResult result)
  318.             {
  319.                 this.innerContext.EndReply(result);
  320.             }
  321.  
  322.             public override void Reply(Message message, TimeSpan timeout)
  323.             {
  324.                 this.innerContext.Reply(message, timeout);
  325.             }
  326.  
  327.             public override void Reply(Message message)
  328.             {
  329.                 this.Reply(message, this.channel.DefaultSendTimeout);
  330.             }
  331.  
  332.             public override Message RequestMessage
  333.             {
  334.                 get
  335.                 {
  336.                     return this.innerContext.RequestMessage;
  337.                 }
  338.             }
  339.         }
  340.     }
  341. }

Again, that’s a lot of code. But that’s a good starting point if you want to do something simple with the message.

Real world scenarios

This has been a busy time at work, so I’ll skip the scenario code for this week’s post. There are some very interesting samples using channels (both server and client ones) at the WCF Channel Extensibility samples page. Also, there are some nice posts from Nicholas Allen about channels in WCF which are a great source of information for low-level WCF details.

[Back to the index]

Comments

  • Anonymous
    February 24, 2012
    Please share the code for this.
  • Anonymous
    February 27, 2012
    Hi Hema, you can simply copy/paste the code in the example (this post doesn't have a full sample like other posts in this series). Copying on IE sometimes doesn't work, in Chrome works all the time for me. And if you want to see a full code sample for a server-side reply channel, you can look at the post at blogs.msdn.com/.../wcf-extensibility-transport-channels-reply-channel.aspx.
  • Anonymous
    February 27, 2012
    Hi Carlos,        Thanks for the reply. I am new to WCF. I am trying to read the poison message in WCF service layer itself. So that I can handle it appropriately. Can you help me on this?
  • Anonymous
    February 27, 2012
    I haven't worked with queues and WCF, but the document at msdn.microsoft.com/.../ms789028.aspx should give you a good starting point on handling poison messages in WCF.
  • Anonymous
    June 22, 2012
    Hi Carlos;Been looking at your code and i wonder where the CreateListener() method gets defined? i don't see it listed anywhere. I have to say WCF is anything but intuitive. It's confusing the heck out of me.
  • Anonymous
    June 22, 2012
    Hi Shawn,Thanks for the comment. I partially agree with you - the WCF channel model is really, really, really complicated (especially with all the factory model / asynchronous methods - as I mentioned in another post, anytime you can avoid going down to the WCF channels, you definitely should. However, the "simple" WCF scenarios (where you define service and operation contracts and that's it) I found fairly simple.Regarding your question about the listener, in the post about transport channels (blogs.msdn.com/.../wcf-extensibility-transport-channels-reply-channel.aspx) there is a complete example for a reply channel. However, for completeness sake, I'll try to update this post with an example of a server-side protocol channel later today.Thanks,Carlos.