MessageViaBinding.Sender:一个控制台应用程序,模拟消息的发送方。
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.Runtime.Serialization; namespace MessageViaBinding.Listener { class Program { static void Main(string[] args) { Uri listenUri = new Uri("http://localhost:8008/listener"); //创建BasicHttpBinding对象 Binding binding = new BasicHttpBinding(); //创建信道监听器对象,listenUri为监听地址 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(CreateReplyMessage(binding)); } } //创建回复消息 static Message CreateReplyMessage(Binding binding) { string action = "urn:artech.com/reply"; string body = "这是一个简单的回复消息!"; return Message.CreateMessage(binding.MessageVersion, action, body); } } }
三、创建发送端应用程序
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; namespace MessageViaBinding.Sender { class Program { static void Main(string[] args) { Uri listenUri = new Uri("http://localhost:8008/listener"); //创建BasicHttpBinding对象 Binding binding = new BasicHttpBinding(); IChannelFactory<IRequestChannel> channelFactory = binding.BuildChannelFactory<IRequestChannel>(); channelFactory.Open(); IRequestChannel channel = channelFactory.CreateChannel(new EndpointAddress(listenUri)); channel.Open(); Message replyMessage = channel.Request(CreateRequestMessage(binding)); Console.WriteLine ("接收到回复消息\n{0}",replyMessage); Console.Read(); } //创建请求消息 static Message CreateRequestMessage(Binding binding) { string action = "urn:artech.com/request"; string body = "这是一个简单的请求消息!"; return Message.CreateMessage(binding.MessageVersion, action, body); } } }
启动监听端
启动发送端发送请求消息,监听端就能马上监听到该请求消息
同时,监听端发送回复消息,发送端接收到该回复消息
原文地址:http://blog.csdn.net/ry513705618/article/details/45392045