当客户端在WCF双工中突然崩溃时该怎么办



我使用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双工。我的WCF客户端应用程序在用户登录到该应用程序时加入此WCF;当用户从客户端应用程序注销时,客户端应用程序将离开WCF。问题是,如果用户突然终止应用程序,并且没有从客户端应用程序注销,那么他/她以后就无法向其他用户发送消息。我检查了这个问题,发现当用户登录(加入)但没有注销(离开)时,在服务器中为用户创建了两个通道,SendAlert在这种情况下不再工作。我该如何解决这个问题?

超时是双工信道的关键设置(如果没有发送或接收消息)。保持短距离,你的频道就会出现故障。如果从服务器发送响应,则可以对出现故障的客户端通道作出反应,并将其从已知通道中删除。如果客户端出现故障,则需要重新加入服务器;在这种情况下,您可以从服务中删除其他回调。

最新更新