我使用WCF双工在服务器上订阅了WCF的用户之间发送/接收消息。WCF有三种方法: Join (订阅)、Leave (取消订阅)和SendAlert (从一个用户向其他用户发送消息)。以下是服务器端代码(服务器中WCF双工的AlertService):
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace RahatWCF
{
[ServiceContract(Name = "AlertService",
Namespace = "RahatWCF",
SessionMode = SessionMode.Required,
CallbackContract = typeof(IAlertCallback))]
public interface IAlert
{
[OperationContract]
int JoinTheConversation(int userId);
[OperationContract(IsOneWay = true)]
void SendAlert(int senderUserId, List<int> recieversUserId, string caption, string messageText);
[OperationContract]
int LeaveTheConversation(int userId);
}
public interface IAlertCallback
{
[OperationContract(IsOneWay = true)]
void NotifyUserOfMessage(int senderUserId, List<int> recieversUserId, string caption, String messageText);
}
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.PerCall)]
public class AlertService : IAlert
{
private static List<IAlertCallback> _callbackList = new List<IAlertCallback>();
public AlertService() { }
public int JoinTheConversation(int userId)
{
IAlertCallback registeredUser = OperationContext.Current.GetCallbackChannel<IAlertCallback>();
if (!_callbackList.Contains(registeredUser))
_callbackList.Add(registeredUser);
return _callbackList.Count;
}
public int LeaveTheConversation(int userId)
{
IAlertCallback registeredUser = OperationContext.Current.GetCallbackChannel<IAlertCallback>();
if (_callbackList.Contains(registeredUser))
_callbackList.Remove(registeredUser);
return _callbackList.Count;
}
public void SendAlert(int senderUserId, List<int> recieversUserId, string caption, string messageText)
{
_callbackList.ForEach(
delegate (IAlertCallback callback)
{
callback.NotifyUserOfMessage(senderUserId, recieversUserId, caption, messageText);
});
}
}
}上面的代码是我在服务器端实现的WCF Duplex。当用户登录到应用程序时,我的WCF客户端应用程序加入此WCF;当用户从应用程序注销时,客户端应用程序离开WCF。问题是,如果用户突然终止应用程序,而不是从客户端应用程序中注销,那么他/她将无法在以后向其他用户发送消息。我检查了这个问题,发现当用户登录(加入)而没有注销(离开)时,在服务器中会为用户创建两个通道,SendAlert在这种情况下不再起作用。我该如何解决这个问题?
发布于 2016-05-16 22:16:10
超时是双工通道的关键设置(如果没有发送或接收到消息)。让它们保持简短,你的通道就会出错。如果您从服务器发送响应,您可以在出错的客户端通道上做出反应,并将其从已知通道中删除。如果客户端出现故障,则需要重新加入服务器;在这种情况下,您可以从服务中删除其他回调。
https://stackoverflow.com/questions/37223557
复制相似问题