Get names of Online users connected to a Server

2019-05-20 04:49发布

问题:

I am new to asp.net. I have gone through this link which has shown how to count the online users connected to a server using asp.net. (which is working when I tried)

My question is: What should I change in that code (Global.asax) so that It shows all the names of the connected users instead of counting them.

I created a chat application which stores the name of the connected user in a variable chatUsername in js file as shown below:

js file

   var chatUsername = window.prompt("Enter Username:", "");
   //
   chat.client.addMessage =  //Function
   //
   chat.server.send(chatUsername); 

.aspx.cs file

//Using SignalR (I think this doesnt matter)
public class Chat : Hub
{
    public void Send(string from)
    {
        // Call the addMessage method on all clients    
        Clients.All.addMessage(from);
    }
}

You can find my complete code here

EDIT: Please provide a simple example related only to asp.net or signalr (no other technologies like MVC)

Please help.

回答1:

Edit: following code refers to SignalR v0.5, not the latest 1.0Alpha2, but I believe the reasoning is the same

To do this you need to add several steps to your SignalR connection process, both in the server and in the client:

on the server side:

  1. on application start-up, for example, you can instantiate a static in-memory repository (can be a dictionary of ) that will serve as the user repository to store all currently connected users.
  2. In the hub you need to handle the Disconnect event (when a user disconnects, needs to be removed from the user repository as well) and notify all other clients that this user disconnected
  3. In the hub you need to add two new methods (the names can be whatever you want) that will help client connect to the system and get the list of currently connected users:
    1. GetConnectedUsers() that just returns a collection of connected users
    2. Joined() where the Hub will create a new User, using the info stored in the round-trip state (the username selected by the client) and the SignalR connection ID, and add the newly created user to the in-memory repository.

on the client side: First you need to instantiate the javascript object that relates to your server-side hub

var chat = $.connection.chat;
chat.username = chatUsername;

Then implements all the functions that will be called by the hub and finally connect to the hub:

    // Step 1: Start the connection
    // Step 2: Get all currenlty connected users
    // Step 3: Join to the chat and notify all the clients (me included) that there is a new user connected
    $.connection.hub.start()
                .done(function () {
                    chat.getConnectedUsers()
                                .done(/*display your contacts*/);
                                    });
                                }).done(function () {
                                    chat.joined();
                                });
                });
});

If you are asking why we need to add a stage like "chat.joined()" is because in the method on the Hub that is handling the connection event, the round-trip state is not yet available, so the hub cannot retrieve the username chosen by the user.

Anyway I made a blog post to show more in detail how to create a basic SignalR chat web application using Asp.Net MVC, and it is available at: http://thewayofcode.wordpress.com/2012/07/24/chatr-just-another-chat-application-using-signalr/

In the post you will also find a link to the github repository where the source is published. I hope this helps.

Valerio



回答2:

Apparently, you are using Signal-R - so try tracking state of online users (i.e. connected clients) in java-script itself. Use Connected/Disconnected/Reconnected server side events to broadcast to all clients - from documentation:

public class Chat : Hub
{
    public override Task OnConnected()
    {
        return Clients.All.joined(Context.ConnectionId, DateTime.Now.ToString());
    }

    public override Task OnDisconnected()
    {
        return Clients.All.leave(Context.ConnectionId, DateTime.Now.ToString());
    }

    public override Task OnReconnected()
    {
        return Clients.All.rejoined(Context.ConnectionId, DateTime.Now.ToString());
    }
}

A global server side store (for example - a static dictionary) can be used to store state against the connection id - that way, this dictionary can give you users for needed connection ids. For example,

// dis-claimer: untested code - just to give the idea/hint/outline
public class Chat : Hub
{
    // change to use Concurrent Dictionary (or do thread-safe access)
    static Dictionary<string, User> _users = new Dictionary<string, User>()

    // call from client when it goes online
    public void Join(string name)
    {
       var connId = this.Context.ConnectionId;
       __users.Add(connId, new User(connId, name));
    }

    public override Task OnConnected()
    {
        return Clients.All.joined(_users[Context.ConnectionId], DateTime.Now.ToString());
    }

    public override Task OnDisconnected()
    {
        var user = _users[Context.ConnectionId];
        _users.Remove(Context.ConnectionId);
        return Clients.All.leave(user, DateTime.Now.ToString());
    }

    public List<User> GetUsers()
    {
       return _users.Values.ToList()
    }

}


回答3:

I think this should work for you :-

   void Application_Start(object sender, EventArgs e)
     {
        // Code that runs on application startup
        Application["OnlineUsers"] = 0;
        List<string> list = new List<string>();
     }
      //First check if it is Authenticated request:-
      void Session_Start(object sender, EventArgs e)
     {
      if(Request.IsAuthenticated)
      list.Add(User.Identity.Name);
       //your rest of code .......
     }

list will return you all the username who are online :-