KimhillZhang  

数据报模式指的是发送端负责把消息发送给对方并且收到确认消息之后就完成交互的方式,发送端唯一确定的就是消息发送成功,但不知道消息是否到达终节点,是否已经被处理,返回结果如何一无所知;

客户端实现IOutputChannel, 服务端采用实现IInputChannel

发送端代码:

using System.ServiceModel.Channels;
using System.ServiceModel;

namespace 客户端Output
{
    class Program
    {
        static void Main(string[] args)
        {
            BindingElement[] bindingElements = new BindingElement[3];
            bindingElements[0] = new TextMessageEncodingBindingElement();
            bindingElements[1] = new OneWayBindingElement();
            bindingElements[2] = new HttpTransportBindingElement();

            //http传输
            CustomBinding binding = new CustomBinding(bindingElements);
            Message message;
            IChannelFactory<IOutputChannel> factor = null;
            IOutputChannel outputChannel = null;
    
                string msgBody = Console.ReadLine();
                message = Message.CreateMessage(binding.MessageVersion, "SendMessage", msgBody);

                //创建消息
                factor = binding.BuildChannelFactory<IOutputChannel>(new BindingParameterCollection());
                factor.Open();
                outputChannel = factor.CreateChannel(new EndpointAddress("http://localhost:9090/InputService"));
                outputChannel.Open();
                outputChannel.Send(message);
                Console.WriteLine("消息已成功发送");
         
            outputChannel.Close();
            factor.Close();
        }
    }
}

 

接收端:

 

using System.ServiceModel.Channels;

namespace 服务端Input
{
    class Program
    {
        static void Main(string[] args)
        {
            BindingElement[] bindingElements = new BindingElement[3];
            bindingElements[0] = new TextMessageEncodingBindingElement();
            bindingElements[1] = new OneWayBindingElement();
            bindingElements[2] = new HttpTransportBindingElement();

            CustomBinding binding = new CustomBinding(bindingElements);
            IChannelListener<IInputChannel> listener = binding.BuildChannelListener<IInputChannel>(new Uri("http://localhost:9090/InputService"), new BindingParameterCollection());

            listener.Open();
            IInputChannel inputChangel = listener.AcceptChannel();
            inputChangel.Open();
            Console.WriteLine("开始接收消息");
            Message message = inputChangel.Receive();
            Console.WriteLine("接收到一条新消息,action为:{0}, body 为{1}", message.Headers.Action, message.GetBody<string>());
            message.Close();
            inputChangel.Close();
            listener.Close();
            Console.Read();
          
        }
    }
}

 摘自:.NET3.5高级编程

posted on 2012-03-27 21:27  KimhillZhang  阅读(571)  评论(0编辑  收藏  举报