MyException - 我的异常网
当前位置:我的异常网» 研发管理 » WCF技术内情 第10章(1)

WCF技术内情 第10章(1)

www.myexceptions.net  网友分享于:2013-04-10  浏览:2次
WCF技术内幕 第10章(1)

第10章 分发器和客户端 Dispatchers and Clients

10.1 问自己的问题

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

namespace ConsoleApplication20
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建绑定 B
            BasicHttpBinding binding = new BasicHttpBinding();

            //创建地址 A
            Uri address = new Uri("http://www.andersoft.com/anders");

            //构建ChannelListener堆栈
            IChannelListener<IReplyChannel> listenerStack = binding.BuildChannelListener<IReplyChannel>(new BindingParameterCollection());

            //打开侦听器堆栈
            listenerStack.Open();

            //创建通道堆栈
            IReplyChannel receiveChannels = listenerStack.AcceptChannel();

            //打开通道堆栈
            receiveChannels.Open();

            //异步接收消息
            receiveChannels.BeginReceiveRequest(new AsyncCallback(ReceiveRequest), receiveChannels);

            //构建通道工厂堆栈
            IChannelFactory<IRequestChannel> channelFactoryStack = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection());

            //打开通道工厂堆栈
            channelFactoryStack.Open();

            //从通道工厂堆栈创建通道堆栈
            IRequestChannel sendChannels = channelFactoryStack.CreateChannel(new EndpointAddress(address));

            //打开通道堆栈
            sendChannels.Open();

            //发送消息给接收者
            Message replyMessage = sendChannels.Request(Message.CreateMessage(MessageVersion.Soap11WSAddressingAugust2004, "urn:SomeRequestAcion", "Hi There"));

            //显示回复的消息内容
            Console.WriteLine("{0}Reply Received:{1}{2}", Environment.NewLine, Environment.NewLine, replyMessage.ToString());

            //清理
            sendChannels.Close();
            channelFactoryStack.Close();
            listenerStack.Close();
        }

        private static void ReceiveRequest(IAsyncResult ar)
        {
            IReplyChannel channels = ar.AsyncState as IReplyChannel;

            //获取requestContext
            RequestContext context = channels.EndReceiveRequest(ar);

            //显示接收消息
            Console.WriteLine("{0}Request Received:{1}{2}", Environment.NewLine, Environment.NewLine, context.RequestMessage.ToString());

            //创建应答消息
            Message reply = Message.CreateMessage(MessageVersion.Soap11WSAddressingAugust2004, "urn:SomeReplyAction", "Hi there back");

            //发送回复
            context.Reply(reply);

            //关闭上下文
            context.Close();

            //关闭通道
            channels.Close();
        }
    }
}


文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有