您的位置:首页 > 其它

WCF面向服务应用程序系列之十六:消息交换模式(MEP)-请求/应答操作

2010-12-19 17:48 561 查看
WCF的消息交换模式指Message Exchange Patterns,主要分为:请求(Request)/应答(Reply)、单向(One Way)、双向(Duplex)或者回调(Callback);

本章主要介绍请求(Request)/应答(Reply)操作,请求/应答操作是所有服务操作的缺省行为;通过查看WSDL描述,我们可以看到<wsdl:input>与<wsdl:output>消息的描述信息;该消息能够包含请求参数,返回数据,<body>元素,或者返回的SOAP错误等。

在请求/应答操作中,客户端以消息形式发出请求,它会阻塞客户端直到收到应答消息。应答的默认超时值为1分钟,如果超过这一时间服务仍然没有应答,客户端就会获得一个TimeOutException异常。请求/应答与经典的客户端/服务端编程模型相似,返回的应答消息包括了返回的结果,或者它会将返回值转换为一般方法的返回值。此外,如果存在通信异常或服务端异常,代理在客户端抛出一个异常。除了NetPeerTcpBinding和NetMsmqBinding绑定,所有的绑定均支持请求/应答操作。

请求/应答的操作模式如下图:



下面我们通过一个DEMO来介绍请求/应答操作:

主要代码如下:

接口代码:

[ServiceContract(Namespace = "http://schemas.xinhaijulan.com/demos/RequestReply")]
public interface IHelloWCF
{
[OperationContract(Name = "GetMessageContract", Action = "urn:AcionInput", ReplyAction = "urn:ActionOutput")]
string GetMessage(string msg);
}


实现类代码:

public class HelloWCF : IHelloWCF
{
public string GetMessage(string msg)
{
return "Message from client is:" + msg;
}
}


服务端代码:

static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(ServiceLibrary.HelloWCF)))
{
host.AddServiceEndpoint(typeof(ServiceLibrary.IHelloWCF), new NetTcpBinding(), "net.tcp://localhost:9000/HelloWCF");
host.Open();
Console.WriteLine("Please input exit to close host.");
string key = Console.ReadLine();
while (key.ToLower() != "exit")
{
Console.WriteLine("Please input exit to close host.");
key = Console.ReadLine();
}
}
}


客户端代码:

static void Main(string[] args)
{
ChannelFactory<ServiceLibrary.IHelloWCF> channelFactory = new ChannelFactory<ServiceLibrary.IHelloWCF>(new NetTcpBinding());
ServiceLibrary.IHelloWCF client = channelFactory.CreateChannel(new EndpointAddress("net.tcp://localhost:9000/HelloWCF"));

using (client as IDisposable)
{
Console.WriteLine("------------Begin-------------");

Console.WriteLine(client.GetMessage("Hello WCF!"));

Console.WriteLine("------------End---------------");
}

Console.ReadLine();
}


运行代码,输出如下:

------------Begin-------------
Message from client is:Hello WCF!
------------End---------------


至此,消息交换模式(MEP)-请求/应答操作介绍完毕。

点击下载DEMO

作者:心海巨澜
出处:http://xinhaijulan.cnblogs.com
版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐