基于TCP协议绑定的WCF双工回调的一般使用方法

问题

今天同事想在TCP绑定的wcf服务的外层包一个webservice,一般的服务都可以进行包装,但遇到有双工回调的wcf服务时,稍微麻烦了点,需要在实例化服务时加上回调实例。

ServiceReference1.AuthenticationServiceClient proxy = new ServiceReference1.AuthenticationServiceClient(instanceContext);

反复测试了几种应用形式,发现只有Silverlight在引用这种双工服务时有无参的重载,其他的都需要一个实现了回调接口的类,那么怎么实现这个类呢?

示例

先定义一个简单的双工服务

[ServiceContract(CallbackContract=typeof(IDemoServiceCallBack))]
    public interface IDemoService
    {
        [OperationContract]
        void Add(int a,int b);
    }
    public interface IDemoServiceCallBack
    {
        void GetResult(int c);
    }
    public class DemoService
    {
        [OperationContract(IsOneWay = true)]
        public void Add(int a,int b)
        {
            var client = OperationContext.Current.GetCallbackChannel<IDemoServiceCallBack>();
            client.GetResult(a + b);
        }
    }

说明:此服务提供了一个加的方法,客户端只需要传递两个整数,服务端计算后会回调客户端接收结果。

客户端调用方式

客户端引用服务后,会发现在实例化时需要自己实现一个回调接口,

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public class MyCallBack : DemoService.IDemoServiceCallBack
    {
        public void GetResult(int c)
        {            
             //得到结果c,并进行下一步处理。            
        }
     }
调用
AddService.IDemoServiceCallback callback = new MyCallBack();
System.ServiceModel.InstanceContext instanceContext = new System.ServiceModel.InstanceContext(callback);
AddService.DemoServiceClient proxy = new AddService.DemoServiceClient(instanceContext);
int c = proxy.Add(1,2);
callback.GetResult(c);

一点想法

至于为什么只有Silverlight中进行无参的实例化,猜想是由于Silverlight的服务调用都是异步的方式原因,当然这里正常的调用方式
还是需要加上双工回调方法实现的。
posted @ 2010-10-28 14:11  翁玉礼  阅读(2756)  评论(4编辑  收藏  举报