标签:
双工模式
描述:双工模式建立在答复模式和单向模式的基础之上,实现客户端与服务端相互的调用。
相互调用:以往我们只是在客户端调用服务端,然后服务端有返回值返回客户端,而相互调用不光是客户端调用服务端,而且服务端也可以调用客户端的方法。
1.添加WCF服务 Service2.svc,并定义好回调的接口,服务器端接口IService2.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfService1
{
//CallbackContract = typeof(IService2CallBack) 定义回调的接口类型
[ServiceContract(CallbackContract = typeof(IService2CallBack))]
public interface IService2
{
[OperationContract]
string ShowName(string name);
}
//回调的接口,该接口中的方法在客户端实现
public interface IService2CallBack
{
//IsOneWay = true 启动单向模式,该模式方法不能有返回值
[OperationContract(IsOneWay = true)]
void PrintSomething(string str);
}
}
2.服务端实现 Service2.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfService1
{
public class Service2 : IService2
{
IService2CallBack callback = null;//回调接口类型
public Service2()
{
//获取调用当前操作的客户端实例
callback = OperationContext.Current.GetCallbackChannel<IService2CallBack>();
}
/// <summary>
/// 被客户端调用的服务
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public string ShowName(string name)
{
callback.PrintSomething(name);
return "服务器调用客户端,WCF服务,显示名称:xsj...";
}
}
}
3.服务器端配置,web.config 在system.serviceModel中添加配置,
支持回调的绑定有4种:WSDualHttpBinding、NetTcpBinding、NetNamedPipeBinding、NetPeerTcpBinding。
我们这里用WSDualHttpBinding为例:
<endpoint address="" binding="wsDualHttpBinding" contract="WcfService1.IService2"></endpoint>
<system.serviceModel>
<services>
<service name="WcfService1.Service2">
<endpoint address="" binding="wsDualHttpBinding" contract="WcfService1.IService2"></endpoint>
</service>
</services>
</system.serviceModel>
标签:
原文地址:http://www.cnblogs.com/xsj1989/p/5729621.html