2

这是我的中心:

[HubName("marketWatch")]
public class MarketWatchHub : Hub
{
    public override Task OnConnected()
    {
        SocketCommunicator.Instance.UserConnected(Context.ConnectionId, Context.User.Identity.Name);

        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        SocketCommunicator.Instance.UserDisconnected(Context.ConnectionId);

        return base.OnDisconnected();
    }

    public override Task OnReconnected()
    {
        // TODO: implement...
        return base.OnReconnected();
    }

    public List<MarketDataResponse> GetAllMarketWatchData()
    {
        return SocketCommunicator.Instance.MarketDataList;
    }
}

这是 SocketCommunicator 类的简化版本:

public class SocketCommunicator
{
    private static SocketCommunicator _Instance = new SocketCommunicator();

    public static SocketCommunicator Instance
    {
        get { return SocketCommunicator._Instance; }
    }

    private Socket socket { get; set; }

    private readonly object lockObj = new object();

    private IHubContext hubContext;

    private List<UserDetail> connectedUsers;

    public List<MarketDataResponse> MarketDataList;

    private SocketCommunicator() { }

    public void UserConnected(string connectionId, string username)
    {
        lock (lockObj)
        {
            connectedUsers.Add(new UserDetail() { ConnectionId = connectionId, UserName = username });
        }
    }

    public void UserDisconnected(string connectionId)
    {
        lock (lockObj)
        {
            connectedUsers.RemoveAll(ud => ud.ConnectionId == connectionId);
        }
    }

    public void GetMarketData()
    {
        // Do something and set this.MarketDataList
    }        
}

当我按 F5 并调试我的应用程序时,它就像一个魅力。当用户登录时,我的集线器中的 OnConnected 方法被调用,当用户注销时,OnDisconnected 方法被调用。但是,如果用户登录并关闭他/她的浏览器,则不会调用 OnDisconnected 方法。这意味着及时,我的 connectedUsers 列表将包含大量未真正连接的 UserDetail 对象。我怎样才能避免这种情况?有没有更好的方法来存储用户 - 连接 ID 关联?

提前致谢,

4

1 回答 1

2

您等待 OnDisconnect 被调用多长时间?它并不总是即时的,特别是如果客户端没有“干净地”关闭(即关闭浏览器)。一旦连接超时,它最终应该被调用。

我有一个类似的设置,它工作正常。

于 2013-05-15T12:43:32.367 回答