SignalR for tracking online users and chat

2020-02-29 05:30发布

问题:

We are working on a social network application and are going to implement couple of new features. 1. Tracking online users 2. Chat (one to one chat and later group chat)

I have looked into SingalR and it seems promising. We are using ASP.NET MVC 3 and are thinking of using hubs. My question to start with is whether SignalR be better instead of simple polling for chat? What will be better as far as scalability is concerned? I have seen other questions on SO but was not able to find out which one of them is better as far as scalability is concerned.

The second question is if we use SignalR, can we use it to also track online users. We can call a server side function from each client at regular interval to say "I am online" and in the hub method we can just set the isOnline bit in the DB. Once the client is disconnected we can unset the bit. Will this work or is simple polling is better here ? How do we set user as offline if we use simple polling?

回答1:

I am using SignalR as a kind-of chat architecture too. Works perfectly an our single IIS server setup. For scalability check out: Sclaing-out-SignalR

If you are using Hubs, you can solve the "I am online" problem by querying the connected clients like this

var clients = Hub.GetClients<Type of your hub here>();

and request the UserID from each client. If there is a loss of any connection you have to find the in DB online users, that are no more clients of the hub.

OR

Another approach is to set the user online as a first message from user to hub. "Hi I am there". And use this solution

public class MyHub : Hub, IDisconnect
{
    public Task Disconnect()
    {
        // Query the database to find the user by it's client id.
        var user = db.Users.Where(u => u.ConnectionId == Context.ConnectionId);
        return Clients.disconnected(user.Name);
    }
}

To handle the disconnect event.

Hope I could give you some ideas.



回答2:

SignalR is better than polling because of the network traffic involved with db connections. Also, think about what version of signalR you'll be using with your MVC project as the latest version of signalR only supports .net 4.5.

As for the number of connections, it depends on how much memory you have and how many connections you have configured in IIS. You can easily handle 1000+ on a decent rig.

As with Tom's answer, you can intercept events to hubs or lower signalR interfaces to get counts, disconnect and connect events.