熟悉WCF的朋友應該都了解WCF的雙工回調,這裡簡單說一下,WCF的服務開放出去後,一旦有用戶端調用,服務端便會保留各個用戶端的一個句柄,然後服務端會在合适的時候做遠端調用來給用戶端傳遞一些資料,這個類似遠端事件綁定的機制非常有用,很多時候可以避免timer的主動請求伺服器,而是由伺服器主動推送資料給用戶端:
然而,這種機制,有一個問題,就是當client注冊到伺服器後,client可能會意外掉線但來不及通知服務端,當服務端再試圖回調此client時,由于回調句柄無法找到用戶端實作而出現異常:
The communication object, System.ServiceModel.Security.SecuritySessionServerSettings+SecurityReplySessionChannel, cannot be used for communication because it has been Aborted.
大概意思就是連接配接已經終止,無法使用連接配接。
為了解決這個問題,我今天晚上特意寫了一個Demo來測試,這個例子是用戶端一旦注冊到伺服器後,伺服器每隔3秒鐘回調一次用戶端并傳給用戶端參數:
服務契約
代碼
[ServiceContract(CallbackContract=typeof(IAddServiceCallBack))] public interface IAddService { [OperationContract] void Login(string name); } [ServiceContract] public interface IAddServiceCallBack [OperationContract(IsOneWay=true)] void ReturnValue(string returnName); }
服務實作
public class AddService:IAddService
public class Client
public string username { get; set; }
public IAddServiceCallBack callbackHandler { set; get; }
static List<Client> list = new List<Client>();
public void Login(string name)
if (list.Where(m => m.username == name).Count() == 0)
list.Add(new Client() { username=name, callbackHandler=OperationContext.Current.GetCallbackChannel<IAddServiceCallBack>() });
static System.Timers.Timer timer;
public static void Start()
timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Start();
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
try
if (DateTime.Now.Second%3 == 0)
list.ForEach(m => m.callbackHandler.ReturnValue("服務端回調:" + m.username));
catch(Exception ex)
RemoveCallBack(
static void RemoveCallBack(string name)
{
if (DIC.ContainsKey(name))
{
DIC.Remove(name);
}
}
為了找出原因,我做了一個有趣的測試,将解決方案編譯後,切到windows資料總管,找到了生成的服務端和用戶端的控制台程式
我開啟了一個服務執行個體和三個client執行個體
<a target="_blank" href="http://blog.51cto.com/attachment/201106/161840215.png"></a>
我試着将第2個client直接關掉,這樣服務端是不知道2已經掉線的,是以在回調2的時候會出現異常,這時會出現什麼問題呢?
<a target="_blank" href="http://blog.51cto.com/attachment/201106/161854184.png"></a>
如上圖,關閉2後,最先注冊到伺服器的用戶端1仍然繼續被伺服器回調,但是在2後注冊到伺服器的3停止被回調,于是猜想出異常的那個用戶端以後的其他用戶端都會停止掉,而之前的不受影響。為了驗證想法,重新做了測試,關閉1後,果然2和3都停止了。
問題确認後,就得有解決辦法,否則留個異常跟吃個蒼蠅沒有什麼差別了。
辦法一,在用戶端的Close或停止的事件中告訴伺服器移除回調句柄,這個方法我首先給排除了,關閉視窗怎麼辦?斷電怎麼辦…用戶端的路走不通了
辦法二,服務端監控用戶端是否離線,心跳包出場,用戶端每5秒鐘想伺服器回發一次,若伺服器監控到某個用戶端的最後更新時間比現在大5秒則做離線處理,移除用戶端。
在僅有的辦法裡,我選了第二個辦法,于是在伺服器端加上了
void Update(string name);
static Dictionary<string, DateTime> dicOfOnLine = new Dictionary<string, DateTime>();
static System.Timers.Timer timer1;
public static void StartListenClients()
timer1 = new System.Timers.Timer();
timer1.Interval = 500;
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
timer1.Start();
static void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
foreach(var item in dicOfOnLine)
if (item.Value.AddSeconds(5) < DateTime.Now)
DIC.ToList().RemoveAll(m => m.Key == item.Key);
具體實作是,當用戶端注冊到伺服器時,伺服器将用戶端添加到一個字典中,這個字典中儲存有用戶端名稱和添加時間,以後由用戶端定時心跳來更新伺服器上的這個字典集合,在服務中會有一個定時器,500毫秒一次去檢測這個集合,如果發現有大于5秒鐘還未更新的用戶端,則從回調句柄集合中移除,由此避免句柄的調用異常問題。
用戶端定時調用update進行更新。
經多次測試,這種異常在IIS下捕獲不了,會直接導緻IIS程序崩潰,Console下異常可以捕獲但是服務有停止的可能性。
源代碼:http://files.cnblogs.com/wengyuli/HostTcpTest.rar
有朋友提醒可以在循環中設定try catch,代碼已經改成
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
string myname = string.Empty;
for (int i = 0; i < DIC.Count;i++)
{
try
{
myname = DIC.ToList()[i].Key;
DIC.ToList()[i].Value.ReturnValue("服務端回調:" + DIC.ToList()[i].Key);
}
catch
DIC.Remove(myname);
}
}
您有更好的辦法嗎?歡迎讨論。
本文轉自wengyuli 51CTO部落格,原文連結:http://blog.51cto.com/wengyuli/586575,如需轉載請自行聯系原作者