WCF技术内幕 第10章(1)

本文通过一个具体的示例展示了如何使用WCF(Windows Communication Foundation)进行服务通信。包括了创建BasicHttpBinding绑定、设置服务地址、构建监听器和服务通道等步骤,并实现了消息的发送与接收。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第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();
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值