监听端创建信道Listener,代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Artech.MessagingVisBinding.Listener
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri listenUri = new Uri("http://127.0.0.1:9999/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(CreateReplyMessage(binding));
            }
        }

        static Message CreateReplyMessage(Binding binding)
        {
            string action = "urn:artech.com/reply";
            string body = "这是一个简单的回复消息!";
            return Message.CreateMessage(binding.MessageVersion, action, body);
        }
    }
}
View Code

发送端创建信息Sender,代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel;

namespace Artech.MessagingViaBinding.Sender
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri listenUri = new Uri("http://127.0.0.1:9999/listener");
            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);
        }
    }
}
View Code

 

posted on 2013-10-22 23:48  chinaagan  阅读(246)  评论(0编辑  收藏  举报