日期:2014-05-18  浏览次数:20729 次

实现服务,双工通信,WCF学习
博客来源:http://blog.csdn.net/fangxinggood/archive/2011/01/15/6142861.aspx

实现服务(工程WcfDuplexMessageService)
(1) 为了所有客户端都注册到一个服务对象上,所以定义服务端为Singleton实例模式:
  InstanceContextMode=InstanceContextMode.Single (Singleton的实例在服务Host启动即实例化)
问题一:“服务端为Singleton实例模式”,是什么?有什么作用?

“注册到一个服务对象上”什么意思?还有不是在一个服务对象上的时候???

(2) 定义了一个static的List<IClient>统一保存客户端回调实例,并公开为Property,便于ServerUI能访问。
(3) 为了防止广播时不会因为客户端关闭而导致服务端异常,监听了Channel.Closing事件
  客户端关闭(Channel被关闭)时就会触发这个事件,在此事件处理中移除该客户端回调实例。
view plaincopy to clipboardprint?

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ServiceModel;  
  4.  
  5. namespace WcfDuplexMessageService  
  6. {  
  7. [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]  
  8. public class MessageService : IMessageService, IDisposable  
  9. {  
  10. public static List<IClient> ClientCallbackList { get; set; }  
  11.  
  12. public MessageService()  
  13. {  
  14. ClientCallbackList = new List<IClient>();  
  15. }  
  16.  
  17. public void RegisterClient()  
  18. {  
  19. var client = OperationContext.Current.GetCallbackChannel<IClient>();
问题二:“OperationContext.Current.GetCallbackChannel”指什么???有什么作用???

  20. var id = OperationContext.Current.SessionId;
指什么?有什么作用???

  21. Console.WriteLine("{0} registered.", id);  
  22. OperationContext.Current.Channel.Closing += new EventHandler(Channel_Closing);  
  23. ClientCallbackList.Add(client);  
  24. }  
  25.  
  26. void Channel_Closing(object sender, EventArgs e)  
  27. {  
  28. lock (ClientCallbackList)  
  29. {  
  30. ClientCallbackList.Remove((IClient)sender);  
  31. }  
  32. }  
  33.  
  34. public void Dispose()  
  35. {  
  36. ClientCallbackList.Clear();  
  37. }  
  38. }  
  39. }  

这个类的主要作用是将客户端实例添加到“ClientCallbackList”中实现注册和管理。

只是不知道“ var client = OperationContext.Current.GetCallbackChannel<IClient>();  
 var id = OperationContext.Current.SessionId; ”这两句处理的什么???

------解决方案--------------------
使用服务操作中的 OperationContext 访问当前操作执行环境。特别是,操作上下文用于访问双工服务中的回调通道、存储整个操作部分的额外状态数据、访问传入消息头和属性以及添加传出消息头和属性。

Current 属性返回表示当前执行上下文的 OperationContext 对象。


使用 Current 属性和 GetCallbackChannel<T> 方法获取从方法中返回调用方的通道

大部分可以写在配置文件里的把~~
------解决方案--------------------
探讨

InstanceContextMode 枚举:指定可用来处理包含在传入消息中的调用的服务实例数。

OperationContext.Current.GetCallbackChannel:获取调用当前操作的客户端实例的通道。

OperationContext.Current:获取或设置当前线程的执行上下文。

OperationContext.Current.SessionId:获……