How to obtain connection ID of signalR client on the server side?

前端 未结 3 1262

I need to get the connection ID of a client. I know you can get it from the client side using $.connection.hub.id. What I need is to get in while in a web servi

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 17:10

    When a client invokes a function on the server side you can retrieve their connection ID via Context.ConnectionId. Now, if you'd like to access that connection Id via a mechanism outside of a hub, you could:

    1. Just have the Hub invoke your external method passing in the connection id.
    2. Manage a list of connected clients aka like public static ConcurrentDictionary... by adding to the dictionary in OnConnected and removing from it in OnDisconnected. Once you have your list of users you can then query it via your external mechanism.

    Ex 1:

    public class MyHub : Hub
    {
        public void AHubMethod(string message)
        {
            MyExternalSingleton.InvokeAMethod(Context.ConnectionId); // Send the current clients connection id to your external service
        }
    }
    

    Ex 2:

    public class MyHub : Hub
    {
        public static ConcurrentDictionary MyUsers = new ConcurrentDictionary();
    
        public override Task OnConnected()
        {
            MyUsers.TryAdd(Context.ConnectionId, new MyUserType() { ConnectionId = Context.ConnectionId });
            return base.OnConnected();
        }
    
        public override Task OnDisconnected(bool stopCalled)
        {
            MyUserType garbage;
    
            MyUsers.TryRemove(Context.ConnectionId, out garbage);
    
            return base.OnDisconnected(stopCalled);
        }
    
        public void PushData(){
            //Values is copy-on-read but Clients.Clients expects IList, hence ToList()
            Clients.Clients(MyUsers.Keys.ToList()).ClientBoundEvent(data);
        }
    }
    
    public class MyUserType
    {
        public string ConnectionId { get; set; }
        // Can have whatever you want here
    }
    
    // Your external procedure then has access to all users via MyHub.MyUsers
    

    Hope this helps!

提交回复
热议问题