Wcf中的信道完成各种通信相关的任务,信道由信道管理器创建。
在不同的消息交换模式下,信道在消息的发送端和接收端所起的作用是不同的。这些各异的信道使用信道形状来描述,不同形状的信道具有不同的作用。对于请求/回复模式下,发送端的信道负责发送消息请求,信道使用接口IRequestChannel表示,接收端的信道负责回复请求,信道使用接口IReplyChannel表示;对于双工通信模式下,消息交换双方地位对等,它们都具有输出和输入功能,这样的信道使用接口IDuplexChannel表示,IDuplexChannel则继承自IOutputChannel和IInputChannel。以上提到的所有接口都继承自IChannel接口。
信道管理器在客户端和服务端的功能也不尽相同,服务端的信道管理器用于监听来自客户端的请求,而客户端的信道管理器仅仅创建用于请求发送和回复接收的信道。因为这些不同,所以服务端和客户端的信道管理器使用不同的对象来表示。信道管理器在客户端被称为信道工厂,使用接口IChannelFactory表示,信道管理器在服务端被称为信道监听器,使用IChannelListener接口表示。
Wcf中,绑定对象创建信道管理器,信道管理器创建信道,信道负责完成相应消息交换模式下被赋予的通信功能。
客户端和服务端可以通过绑定对象直接进行消息的传递。
服务端的代码如下所示。代码中绑定对象负责创建信道监听器,信道监听器负责创建信道,接着在循环中获取客户端请求,并组织消息进行回复。
Uri listenUri = new Uri("http://127.0.0.1:1111/listener");
Binding binding = new BasicHttpBinding();
IChannelListener<IReplyChannel> channelListener = binding.BuildChannelListener<IReplyChannel>(listenUri);
channelListener.Open();
IReplyChannel channel = channelListener.AcceptChannel(TimeSpan.MaxValue);
channel.Open();
Console.WriteLine("开始监听...");
while (true)
{
RequestContext requestContext = channel.ReceiveRequest(TimeSpan.MaxValue);
Console.WriteLine("接收到请求消息:\n{0}", requestContext.RequestMessage);
requestContext.Reply(Message.CreateMessage(binding.MessageVersion, "reply", "回复消息"));
}
下面是客户端的请求代码,同样是绑定对象创建信道工厂,信道工厂创建信道,信道负责发送消息到服务端。
Uri listenUri = new Uri("http://127.0.0.1:1111/listener");
Binding binding = new BasicHttpBinding();
IChannelFactory<IRequestChannel> channelFactory = binding.BuildChannelFactory<IRequestChannel>(listenUri);
channelFactory.Open();
IRequestChannel channel = channelFactory.CreateChannel(new EndpointAddress(listenUri));
channel.Open();
Message replyMessage = channel.Request(Message.CreateMessage(binding.MessageVersion, "yyyy", "请求消息"));
Console.WriteLine("接收到回复消息\n{0}",replyMessage);
Console.Read();