WCF 之 通過綁定進行消息通信
來源:程序員人生 發布時間:2015-05-25 09:14:25 閱讀次數:2639次
WCF可以分成兩個部份:服務模型層(Service Model Layer)和信道層(Channel Layer).服務模型層建立在信道層之上,提供了1個統1的、可擴大的編程模型。信道層則通過綁定創建的信道棧為消息通訊提供了1個傳輸、處理的通道。
綁定與信道棧(Binding and Channel Stack)
綁定,在WCF全部結構體系中扮演著中間人的角色。當服務被成功寄宿時,WCF通過終結點的綁定對象創建1個或多個信道監聽器(ChannelListener),綁定到監聽端口進行要求的偵聽。當要求消息抵達,則利用信道監聽器創建的信道棧進行消息的接收。服務操作履行的結果終究封裝到回復消息中,通過相同的信道棧被回送。在客戶端,通過綁定創建信道工廠(ChannelFactory),借助信道工廠創建的信道棧進行要求消息的發送與回復消息的接收。
下面我們就具體來看1個通過綁定進行消息通訊的實例
1、創建全部解決方案
MessageViaBinding.Listener:1個控制臺利用程序,摹擬消息的監聽方。
MessageViaBinding.Sender:1個控制臺利用程序,摹擬消息的發送方。

2、創建監聽端利用程序
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("接收到要求消息:
{0}", requestContext.RequestMessage);
requestContext.Reply(CreateReplyMessage(binding));
}
}
//創建回復消息
static Message CreateReplyMessage(Binding binding)
{
string action = "urn:artech.com/reply";
string body = "這是1個簡單的回復消息!";
return Message.CreateMessage(binding.MessageVersion, action, body);
}
}
}
3、創建發送端利用程序
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 ("接收到回復消息
{0}",replyMessage);
Console.Read();
}
//創建要求消息
static Message CreateRequestMessage(Binding binding)
{
string action = "urn:artech.com/request";
string body = "這是1個簡單的要求消息!";
return Message.CreateMessage(binding.MessageVersion, action, body);
}
}
}
啟動監聽端

啟動發送端發送要求消息,監聽端就可以馬上監聽到該要求消息

同時,監聽端發送回復消息,發送端接收到該回復消息

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈