WCF系列教程之消息交换模式之请求与答复模式(Request/Reply)

时间:2022-02-15 01:54:10

1、使用WCF请求与答复模式须知

(1)、客户端调用WCF服务端需要等待服务端的返回,即使返回类型是void

(2)、相比Duplex来讲,这种模式强调的是客户端的被动接受,也就是说客户端接受到响应后,消息交换就结束了

(3)、在这种模式下,服务端永远是服务端,客户端就是客户端,职责分明。

(4)、它是缺省的消息交换模式,设置OperationContract便可以设置为此种消息交换模式

2、代码示例

服务层接口IReqReplyService.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks; namespace IService
{
[ServiceContract]
public interface IReqReplyService
{
[OperationContract]
void HelloWorld(string name);
}
}

服务层接口IReqReplyService.cs的实现类代码如下:

using IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace Service
{
public class ReqReplyService : IReqReplyService
{
public void HelloWorld(string name)
{
Thread.Sleep();
}
}
}

修改宿主配置文件App.config如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="Service.ReqReplyService" behaviorConfiguration="OneWayBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/ReqReplyService/"/>
</baseAddresses>
</host> <endpoint address="" binding="wsHttpBinding" contract="IService.IReqReplyService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services> <behaviors>
<serviceBehaviors>
<behavior name="OneWayBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel> </configuration>

生成解决方案,开启宿主服务,并通过微软的svcutil工具生成ReqReplyService服务的客户端代理类,开始菜单/Microsoft Visual Studio 2012/Visual Studio Tools/Visual Studio 2012开发人员命令提示工具,定位到当前客户端WCF系列教程之消息交换模式之请求与答复模式(Request/Reply)l路径,输入命令:svcutil http://localhost:8000/ReqReplyService/?wsdl  /o:ReqReplyService.cs,生成客户端代理类,生成成功之后,将文件添加到项目中.

修改客户端调用方法,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Client.ReqReplyServiceRef; namespace Client
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("****************请求响应通讯服务示例*******************");
ReqReplyClient proxy = newReqReplyClient();
Console.WriteLine("方法调用前时间:" + System.DateTime.Now);
Console.WriteLine(proxy.SayHello("WCF"));
Console.WriteLine("方法调用后时间:" + System.DateTime.Now);
Console.Read();
}
}
}

WCF系列教程之消息交换模式之请求与答复模式(Request/Reply)

我们可以看到服务器响应的时间刚好为6s,正好是线程休眠的时间,并且客户端返回了信息Hello WCF.