WCF如何通过Binding进行通信

  Windows Communication Foundation,顾名思义,就是一个在Windows平台下进行如何进行Communication的基础构造(Infrastructure)。 由于WCF的核心还是Communication,这个新的系列就先来讨论WCF如何进行Communication的。通过本篇文章,你将对WCF的通 信机制有一个总体的认识,了解到一些和通信相关的概念, 比如:Communication、Channel、Channel Listener、Channel Factory、BindingElement、Channel  Shape等等。

  我们已经很清楚了,WCF的通信是通过Endpoint来完成的:Service Provider将WCF service通过Endpoint暴露出来供Service consumer调用,而Service consumer通过与之相匹配的Endpoint来调用service。"Endpoint=ABC”,大家一定也 牢记于心。就Endpoint包含的这3个元素而言,Address解决了寻址的问题,代表如何定位和标识对应的Endpoint,而Contract在 对Service提供的功能、操作(Service Contract)以及数据(Data contract、Message contract和Fault contract)的抽象表示。而真正实现了通信功能的则是Binding

一、Binding实现了所有的通信细节

  总体上讲, WCF主要有两个层次构成:Channel Layer和Service Layer. 前者通过Channel Stack实现Message的传输,而后者对开发人员提供了一个Programming Mode。对于一般的WCF开发人员,不会接触到Channel Layer,而只会调用Service Layer提供的API而以。

  但是,如果你需要真正地认识WCF 整个通信框架,对Channel Layer的了解绝对是有必要的。在我看来,WCF最吸引我的地方不是它自己为我们提供了完备的通信相关的实现,而在于WCF是一个极具可扩展性的 通信框架,无论是Channel Layer还是Service Layer,我们都可以通过WCF Extension对WCF进行自由的扩展以适应我们的具体需求, 在本系列后续的文章中我将向大家介绍一系列有用的扩展。如何你想充分利用WCF提供给我们的扩展性,对Channel Layer的了解基本上是必须的。

  严格地讲,Binding是Service Layer层面上的概念,不过它是由Service Layer转入Channel的入口,也是从Channel Layer到Service Layer的中介。我们说Binding实现了所有通信细节,是站在Service Layer角度来讲的。至于Binding如何实现通信细节,则是通过Channel Layer来实现的。

  为了让大家对Binding如何实现通过现有一个感性的认识,我们来看一个简单的例子。

三、 Demo: 直接通过Binding进行通信

  这个例子通过简简单单的几行代码,通过BasicHttpBinding实现了通信的全过程。该程序很想我们传统的基于Socket的程序:Server端Listen request=>Accept request=>Process request=>Send reply;Client端Send request=>Receive reply。此外通过这个这个简单的程序,将引出Channel Layer一系列重要的对象,比如Channel、RequestChannel、ReplyChannel、Channel Listener和Channel Factory等等。整个应用有两个Console application构成,分别模拟Server和Client.

Demo: 直接通过Binding进行通信

  我们先来看看Server端的代码: 

   1: namespace Artech.MessagingViaBinding.Server
   2: {
   3:     class Program
   4:     {
   5:         static void Main(string[] args)
   6:         {
   7:             Uri address = new Uri("http://127.0.0.1:9999/messagingviabinding");
   8:             BasicHttpBinding binding = new BasicHttpBinding();
   9:             IChannelListener<IReplyChannel> channelListener = binding.BuildChannelListener<IReplyChannel>(address);
  10:             channelListener.Open();
  11:             IReplyChannel channel = channelListener.AcceptChannel();
  12:             channel.Open();
  13:             Console.WriteLine("Begin to listen  ");
  14:             while (true)
  15:             {
  16:                 RequestContext context = channel.ReceiveRequest(new TimeSpan(1, 0, 0));
  17:                 Console.WriteLine("Receive a request message:\n{0}", context.RequestMessage);
  18:                 Message replyMessage = Message.CreateMessage(MessageVersion.Soap11, "http://artech.messagingviabinding", "This is a mannualy created reply message for the purpose of testing");
  19:                 context.Reply(replyMessage);
  20:             }
  21:         }
  22:     }
  23: } 

  我来简单介绍一些上面这段代码的逻辑:

  • 创建Uri对象,代表监听的URI:
       1: EndpointAddress address = new EndpointAddress(http://127.0.0.1:9999/messagingviabinding);
  • 创建BasicHttpBinding对象,我们正是通过它来使用所有的通信功能:
       1: BasicHttpBinding binding = new BasicHttpBinding();
  • 通过binding对象创建IChannelListener对象,并调用Open方法打开它:
       1: IChannelListener<IReplyChannel> channelListener = binding.BuildChannelListener<IReplyChannel>(address);
       2: channelListener.Open();
  • 通过IChannelListener对象创建IReplyChannel 并调用Open方法打开它:
       1: IReplyChannel channel = channelListener.AcceptChannel();
       2: channel.Open();
  • 在While循环中监听来自client端的request,一旦request抵达, 调用IReplyChannel 的ReceiveRequest方法,并得到一个RequestContext 对象,通过RequestContext 对象可以得到request message并打印出来:
       1: RequestContext context=channel.ReceiveRequest(new   TimeSpan(1,0,0));
       2: Console.WriteLine("Receive a request message:\n{0}", context.RequestMessage);
  • 创建一个Reply message,借助得到的RequestContext 对象发送回client端:
       1: Message replyMessage = Message.CreateMessage(MessageVersion.Soap11, "http://artech.messagingviabinding", "This is a mannualy created reply message for the purpose of testing");
       2: context.Reply(replyMessage); 

  再来看看Client端的代码: 

   1: namespace Artech.MessagingViaBinding.Client
   2: {
   3:     class Program
   4:     {
   5:         static void Main(string[] args)
   6:         {
   7:             EndpointAddress address = new EndpointAddress("http://127.0.0.1:9999/messagingviabinding");
   8:             BasicHttpBinding binding = new BasicHttpBinding();
   9:             IChannelFactory<IRequestChannel> chananelFactory = binding.BuildChannelFactory<IRequestChannel>();
  10:             chananelFactory.Open();
  11:             IRequestChannel channel = chananelFactory.CreateChannel(address);
  12:             channel.Open();
  13:             Message requestMessage = Message.CreateMessage(MessageVersion.Soap11, "http://artech/messagingviabinding", "The is a request message manually created for the purpose of testing.");
  14:             Message replyMessage = channel.Request(requestMessage);
  15:             Console.WriteLine("Receive a reply message:\n{0}", replyMessage);
  16:             channel.Close();
  17:             chananelFactory.Close();
  18:             Console.Read();
  19:         }
  20:     }
  21: }

  我们也来简单分析一下上面这段代码的逻辑:

  • 创建EndpointAddress 对象,这和Server的Uri一致,代表请求的地址:
       1: EndpointAddress address = new EndpointAddress(http://127.0.0.1:9999/messagingviabinding);
  • 创建BasicHttpBinding对象,通过实现向Server端的发送Request,并接收Reply:
       1: BasicHttpBinding binding = new BasicHttpBinding();
  • 通过Binding对象创建IChannelFactory对象并调用Open方法打开它:
       1: IChannelFactory<IRequestChannel> chananelFactory= binding.BuildChannelFactory<IRequestChannel>();
       2: chananelFactory.Open();
  • 通过IChannelFactory对象创建IRequestChannel 对象并调用Open方法打开它:
       1: IRequestChannel channel = chananelFactory.CreateChannel(address);
       2: channel.Open();
  • 创建Request message通过Channel对象发送到Server端,Request方法调用会返回一个Message对象代表从Server端发送回来的Reply message:
       1: Message requestMessage = Message.CreateMessage(MessageVersion.Soap11, "http://artech/messagingviabinding", "The is a request message manually created for the purpose of testing.");
       2: Message replyMessage = channel.Request(requestMessage);
       3: Console.WriteLine("Receive a reply message:\n{0}", replyMessage); 

  我们来看看程序运行的结果,下面是Client端的截图:

WCF如何通过Binding进行通信

  这是Server端的截图:

WCF如何通过Binding进行通信

三、信道( Channel)

  同传统的通信框架一样, 比如.NET Remoting,最终的通信功能通过Communication Channel来实现。同.NET Remoting一样,在Messaging过程中需要实现不同功能实现, 比如Transport、Encoding、Security、Transaction Enlist、Reliable Messaging、Compression、Logging等等,这些功能不可能有一个单一的Channel来实现。从可扩展性考虑,我们也没有必要、也没有可能创建一个万能Channel,我们希望的情况是这样的:一个Channel专注于Messaging过程中某个单一的功能实现,当我们需要某个具体的功能的时候,可以通过插件的形式自由地将对应的Channel加进来就可以了。 而WCF本身也是这样设计的:整个Messaging过程通过一连串Channel来实现,这些Channel按照一定的顺序组成一个Channel stack。由于Messaging首先是基于某种Protocol的Transport, 比如http、TCP、MSMQ、ICP等等,Transport channel在Channel stack中一定是必须的。而且对Transport channel在整个channel stack的位置也有固定的要求:在Sender方的最后一个,Receiver方的第一个。

  不管Channel具体完成怎样的功能,他们都可以看成是一个个Message处理器,这包括为了某种需求添加、修改Soap header;压缩整个Message、或者Message body; 对Message进行签名或者加密等等。

  在WCF中,所有的Channel都直接或者间接实现一个 Interface:System.ServiceModel.Channels.IChannel。通过一个WCF还定义了一个base class:ChannelBase。ChannelBase实现了一些Channel基本的功能,所以我们在自定义Channel的时候一般继承 ChannelBase。

四、 信道形状(Channel Shape)

  由于WCF在进行Messaging的时候可以采用不同的消息交换模式(MEP-Message Exchange Pattern)。 在不同的MEP中,发送方Channel和接收方Channel在Messaging中所扮演的角色是不相同的。比如我们最常见的 Request/Reply MEP中,发送方负责向接收方发送请求并接受回复,而接收方则负责向发送方回复请求,所以发送方的Channel是一个Request Channel,接收方Channel是一个Reply Channel。而对于One-way MEP中,发送方只需要向接收方而不需要接收来自接受方的回复,而对于接收方来说,仅仅需要接受来自发送方的消息而不需要向发送放回复消息,所以One- way发送方的Channel是一种Output Channel,而接收方的Channel是Input Channel。而对于Duplex 方式进行Messaging双方具有相同角色,即负责相对方发送消息,又需要接受对方发送过来的消息,所以此种MEP对应的Channel是Duplex Channel。实际上Duplex Channel = Output Channel + Input Channel。

  WCF专门用一个专门的术语来表述这种不能得MEP对消息交互双方Channel的不同要求:Channel Shape。我们常见的Channel Shape有以下四种:

  • Datagram:数据报方式,采用One-way的消息交换模式。
  • Request/Reply:请求/恢复方式,采用传统的Request/Reply 消息交换模式。
  • Duplex:双向通信,采用Duplex消息交换模式。
  • P2P :点对点方式通信, 采用Duplex消息交换模式。

  由于在不同的MEP中,消息交互双方Channel在整个消息交换过程所扮演的角色时不同的。同理,对于不同 Channel shape, 消息的发送放和接受方需要不同的Channel。System.ServiceModel.Channels namespace定义了相应的Channel interface来表示这些Channel:IRequestChannel, IReplyChannel, IOutputChannel, IInputChannel, IDuplexChannel。这些channel interface与Channel shape之间的对应关系如下表所示:

MEP Sender Receiver
Datagram IOutputChannel IInputChannel
Request/Reply IRequestChannel IReplyChannel
Duplex IDuplexChannel IDuplexChannel
P2P IDuplexChannel IDuplexChannel

  我们回顾一下我们上面的Sample,是否还记得在Client端代码中,我们通过IChannelFactory 对象的CreateChannel方法创建了一个IRequestChannel, 而在Server端的代码中通过IChannelListener对象的AcceptChannel方法创建了一个IReplyChannel。那就是应 该我们模拟的是传统的Request/Reply MEP。

五、 Channel Manager: Channel Listener & Channel Factory

  通过上面的介绍,我们知道了所有的Messaging功能最终都是通过Channel stack来完成的。但是我们在什么时候创建这些Channel,通过什么方式创建它们呢?

  在WCF中,这些Channel对象,无论是处于发送方还是接受方,都不会直接创建他们。所有创建channel的 功能都是通过一组特殊的对象来实现的。我们把这类对象叫做Channel Manager。不过Channel Manager这个名字不是很常用。你可以经常通道的是它的两个别名:Channel Listener和Channel Factory.

  对于Channel的创建,创建方式在发送方和接收方是完全不一样的。对于方法来将,channel的创建方式和简 单,也很直接,就是单纯的创建Channel并使用它向接受方发送消息,并接受恢复(如果不是Datagram  channel shape),说发送方的Channel manager本质上就是一个Channel  factory。

  而对于接受方来讲,Channel manager实际上起着监听者的作用。它和一个固定的Uri绑定,不断监听来自不同发送方的请求,一旦某个请求被监听到,channel manager创建一个Channel来接受该请求,所以接受方的Channel manager被称作Channel listener。

  一个一个channel连接形成一个Stack,通过一个个的Channel factory或者Channel listener也形成一个Stack。所以我们经常所说的Channel stack往往只的是Channel stack & Channel factory/listener stack.

  我们在回到我们上面的Sample,对于Client端的IRequestChannel对象是通过我们创建的 IChannelFactory的CreateChannel方法创建,而Server端的IReplyChannel则是通过 IChannelListener的AcceptChannel方法创建。

六、Binding & Binding Element

  通过以上的叙述,我们实际上对WCF channel layer进行了大致的介绍。我们说channel layer处于Service layer以下,而且一般的WCF开发人员一般不会直接和Channel layer进行交互,而仅仅会通过Service layer提供的API来实现WCF提供的功能。channel layer和Service layer是通过什么方式实现无缝的连接呢?答案是Binding.

  上面我们说了所有的消息交互功能都是通过Channel stack来实现,而组成Channel stack的一个个的Channel又是通过Channel factory和Channel listener来创建的。Channel factory 和Channel listener又是通过什么创建的呢?答案也是Binding。这点通过我们上面的Sample也可以看出来:我们通过 BasicHttpBinding的BuildChannelFactory方法和BuildChannelListener方法创建了 IChannelFactory对象和IChannelListener对象。

   1: IChannelFactory<IRequestChannel> chananelFactory= binding.BuildChannelFactory<IRequestChannel>();
   2: IChannelListener<IReplyChannel> channelListener = binding.BuildChannelListener<IReplyChannel>(address); 

  我们在进一步深究Binding是如何创建IChannelFactory对象和IChannelListener对象。一个Binding由 BindingElement collection组成, 构成BindingElement collection的元素是一个个的BindingElement。BindingElement的最重要的功能就是创建 IChannelFactory和IChannelListener对象。每个BindingElement继承自BindingElement abstract class 。下面是BindingElement的定义:

   1: public abstract class BindingElement
   2: {
   3:     // Methods
   4:     protected BindingElement();
   5:     protected BindingElement(BindingElement elementToBeCloned);
   6:     public virtual IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context);
   7:     public virtual IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context) where TChannel : class, IChannel;
   8:     public virtual bool CanBuildChannelFactory<TChannel>(BindingContext context);
   9:     public virtual bool CanBuildChannelListener<TChannel>(BindingContext context) where TChannel : class, IChannel;
  10:     public abstract BindingElement Clone();
  11:     internal T GetIndividualProperty<T>() where T : class;
  12:     public abstract T GetProperty<T>(BindingContext context) where T : class;
  13:     internal virtual bool IsMatch(BindingElement b);
  14: } 

七、 如何对Channel Layer进行扩展

  在上面已经说了,WCF的一个最大的特性在于具有很强的扩展性。无论是Channel Layer还是Service,你都可以很自由地进行扩展,而这些扩展在具体的项目中往往具有很强的使用性。在我当前的项目中,我就使用了很多这方面的扩 展,在后续的章节中,我将会将这些与大家分享。

  对于Channel Layer的扩展,一般集中在通过创建一些自定义的Channel来完成现有Channel不能完成的功能,比如你可以需要创建一个channel来完成 对Message Body的压缩功能。单独创建channel往往是不够的,我们需要创建与之配套的其他的一些对象,不如Channel factory、Channel listener、Binding element等等。

来源:http://www.cnblogs.com/artech/archive/2008/07/08/1237902.html

加支付宝好友偷能量挖...


评论(0)网络
阅读(134)喜欢(0)Asp.Net/C#/WCF