2
這裏是我的樞紐:Signalr - 關聯的用戶名與connectionIds
[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方法。這意味着我的連接用戶列表將包含大量並未真正連接的UserDetail對象。我怎樣才能避免這種情況?有沒有更好的方式來存儲用戶連接ID關聯?
在此先感謝,
你是對的@Bargaust。在這之後,我發現了一個更好的實現,它支持一個用戶的多個連接。 http://www.tugberkugurlu.com/archive/mapping-asp-net-signalr-connections-to-real-application-users感謝您的回答。 – anilca