使用WCF信道进行基本通信

在使用WCF进行通信是主要是通过配置Binding来改变其通信策略的,不进行Binding配置,也可以使用WCF内置的Binding封装
来实现一个类似于Socket的基本通信,便于理解WCF的实现策略:
Listener:

Uri address = new Uri("http://127.0.0.1:8888/baseService");

BasicHttpBinding binding = new BasicHttpBinding();//使用WCF集成的HttpBinding

IChannelListener<IReplyChannel> channelListener

    = binding.BuildChannelListener<IReplyChannel>(address);//创建信道Manager

channelListener.Open();

Console.WriteLine("Listener is opening");

IReplyChannel channel = channelListener.AcceptChannel();//创建Reply信道

Console.WriteLine("Accept Channel");

channel.Open();//打开信道

Console.WriteLine("channel is opening");

while (true)

{

    RequestContext context = channel.ReceiveRequest();//在信道上监听到Request

    Console.WriteLine("--receive message--");

    Console.WriteLine(context.RequestMessage.GetBody<string>());//获取信道上发送过来的Message

    Console.WriteLine("--receive message—");

    //创建回复信息,包括信息版本,action,和信息内容
    Message reply = Message.CreateMessage(MessageVersion.Soap11, "http://message", "test use message");

    //在信道上发布回复信息
    context.Reply(reply);

}

 

Sender:

EndpointAddress address = new EndpointAddress("http://127.0.0.1:8888/baseService");

BasicHttpBinding binding = new BasicHttpBinding();

IChannelFactory<IRequestChannel> channelFactory

    = binding.BuildChannelFactory<IRequestChannel>();//创建信道Manager

channelFactory.Open();

Console.WriteLine("channel factory opening");

IRequestChannel channel = channelFactory.CreateChannel(address);//创建request信道

channel.Open();

Console.WriteLine("channel opening");

Message requestMess = Message.CreateMessage(MessageVersion.Soap11, "http://messagerequest", "test message from client");

//向信道上发送信息并获取回复信息
Message replyMessage = channel.Request(requestMess);

Console.WriteLine("--service reply:--");

Console.WriteLine(replyMessage.GetBody<string>());

Console.WriteLine("--service reply:--");

channel.Close();

channelFactory.Close();

 

这个例子中使用的通信为Request/Reply通信,使用到的信道manager分别为IChannelFactory和IChannelListener他们都是由binding创建的,也就说都遵循定义的binding策略,其中IChannelFactory用于在发送端创建信道,IChannelListener用于在接收端创建信道

 

除了Request/Reply MEP(Message Exchange Pattern信息交换模式)外WCF的MEP还有:

Datagram(即One-Way信道,用于Sender和Listener的单次通信)

   sender端使用IOutputChannel信道,用于使用信道发送信息

   listener端使用IInputChannel信道,用于接收发送的信息

Duplex和P2P(即双工信道)

   sender端和listener端均使用IDuplexChannel信道进行发送和接收信息

你可能感兴趣的:(WCF)