正如我的标题所写,
背景: 我有 2 种不同类型的应用程序 (WPF-silverlight),它们可以相互通信——医生应用程序和患者应用程序——但这并不意味着只有 2 个应用程序会运行,例如: 我可以运行 3 个医生应用程序和 7 个病人应用程序。 所有这些应用程序都通过 tcp 连接使用 wcf 进行通信。 通信是实时的(如 Messenger 应用程序)
流 每次有应用程序在线(运行)时,我都会在 wcf 上注册它的连接,因为我需要让其他应用程序知道(实时)有新客户端连接或有新客户端断开连接。
问题: 可以让其他应用程序知道有传入的应用程序/客户端, 但我的问题是,如果此客户端已断开连接,如何让其他应用知道,
如果用户正确关闭应用程序(例如单击关闭按钮)就没问题 - 所以在 wpf 中,我可以调用 wcf 来注销连接,
但是如果连接异常终止怎么办(例如直接拔掉你电脑的电源线) 我有什么办法可以知道这个客户端是否仍然连接?
当我在我的 VS2008 中按 f5 并关闭,然后再次打开并关闭(重复)时,我意识到了这个问题,然后,当我调试时,仍然有很多连接存储在那里,但实际上客户端已经被破坏了。
所以有人知道这个最佳解决方案吗? 非常感谢示例
我的代码片段:
Dictionary<Guid, Client> Connections = new Dictionary<Guid, Client>();
// above is the variable where i put the connections
object syncObj = new object();
public ITcpServiceCallback CurrentCallback { get { return OperationContext.Current.GetCallbackChannel<ITcpServiceCallback>(); } }
// this function is called when the program started
public List<Client> ShakeHand( Client client, RoleType appType ) {
if( GetClientsByCallback( CurrentCallback ).Count < 1 && GetClientsByID( client.ID ).Count < 1 ) {
List<Client> retVal = new List<Client>();
lock( syncObj ) {
if( appType == RoleType.Doctor ) {
List<Client> doctors = Helpers.GetDoctor( AppDomain.CurrentDomain.BaseDirectory + "App_Data/doctor.xml" );
foreach( Client doctor in doctors ) {
doctor.Status = ConnectionStatus.Offline;
foreach( Client con in Connections.Values ) {
if( con.Role == RoleType.Doctor && con.ID == doctor.ID ) {
doctor.Status = ConnectionStatus.Online;
break;
}
}
retVal.Add( doctor );
}
} else { //b la.. bla similiar like if above
}
client.Callback = CurrentCallback;
client.Status = ConnectionStatus.Online;
// this is the code where i add the connection
Connections.Add( Guid.NewGuid(), client );
}
return retVal;
}
return null;
}
提前致谢
最佳答案
我认为您真正需要实现的是发布者/订阅者服务。所有医生和患者应用程序都有一个指向发布/订阅服务的链接。当一个应用程序启动时,它会订阅该服务并开始接收来自所有其他应用程序的通知。当应用程序关闭时,它会取消订阅事件。
看看这个: http://msdn.microsoft.com/en-us/library/ms752254.aspx
还有这个: http://msdn.microsoft.com/en-us/magazine/cc163537.aspx
关于wpf - WCF如何检测客户端是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2865752/