SignalR: how to survive accidental page refresh

一个人想着一个人 提交于 2019-12-29 06:27:07

问题


Imagine there is a chat web app between two browser clients using SignalR. What is the best approach to survive accidental F5 hit done by one of the client?

Here is described the strategy using cookies together with custom SignalR IConnectionIdFactory. But the author of the article says "The SignalR team doesn’t recommend this action". So what is the recommended architecture?


回答1:


You can map the temporary connection id to a permanent user id/name (which might be stored in your DB) when the client connects. See the ShootR example which does this (last time I checked, at least). For example, you could keep a ConcurrentDictionary of objects representing users that you track active users with and associate them with their connection ids in OnConnected (and revert this in OnDisconnected) similar to this:

private static readonly ConcurrentDictionary<string, User> Users 
    = new ConcurrentDictionary<string, User>();

public override Task OnConnected() {   
    string userName = Context.User.Identity.Name;
    string connectionId = Context.ConnectionId;

    var user = Users.GetOrAdd(userName, _ => new User {
        Name = userName,
        ConnectionIds = new HashSet<string>()
    });

    lock (user.ConnectionIds) {   
        user.ConnectionIds.Add(connectionId);
    }

    return base.OnConnected();
}


来源:https://stackoverflow.com/questions/20520874/signalr-how-to-survive-accidental-page-refresh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!