WCF双工通信
原创
©著作权归作者所有:来自51CTO博客作者wx636b6259489d3的原创作品,请联系作者获取转载授权,否则将追究法律责任
1、服务
服务必须定义回调函数的接口
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract=typeof(IServiceDuplexCallback))]
public interface IServiceClass
{
[OperationContract(IsOneWay=true)]
void AddNumber(int number);
[OperationContract(IsOneWay=true)]
void SubtractNumber(int number);
}
public interface IServiceDuplexCallback
{
[OperationContract(IsOneWay = true)]
void Calculate(int result);
}IServiceDuplexCallback callback
{
get { return OperationContext.Current.GetCallbackChannel<IServiceDuplexCallback>(); }
}
2、绑定
绑定方式需要选择:wsDualHttpBinding,双工通信
<endpoint address="" binding="wsDualHttpBinding" contract="WCFService.IServiceClass"/>
3、客户端调用
客户端实现接口
public class CallbackHandler : TCP.IServiceClassCallback
{
public void Calculate(int result)
{
MessageBox.Show(result.ToString());
}
}
将实现接口实例作为参数传到服务
InstanceContext ic = new InstanceContext(new CallbackHandler());
TCP.ServiceClassClient client = new WCFClientApp.TCP.ServiceClassClient(ic);
client.AddNumber(val1);
client.AddNumber(val2);
//client.Close();