Search code examples
c#asp.netsignalrsignalr-hubsignalr.client

SignalR - Send message OnConnected


I've been experimenting with SignalR today and It's really neat. Basically what I wanted to achieve is the following:

As soon as a device connects it should send a message to the first one. If there are more devices than 1 connected I would like to send two messages. One to all except the last connected client. And one message to only the last connected client.

The code I've been using works perfect when I place it in a custom API controller and basically call the action, but that's not what I want.

I would like to send the messages as soon as a device connects within OnConnected without any user interaction, but when I place my code inside the OnConnected override it stops working. It doesn't send to the specific clients anymore (first connected and last connected).

I hope someone is able to help me out with this, because I've been banging my head for a few hours now.

    public override System.Threading.Tasks.Task OnConnected()
    {
        UserHandler.ConnectedIds.Add(Context.ConnectionId, UserHandler.ConnectedIds.Count + 1);

        int amountOfConnections = UserHandler.ConnectedIds.Count;
        var lastConnection = UserHandler.ConnectedIds.OrderBy(x => x.Value).LastOrDefault();
        var allExceptLast = UserHandler.ConnectedIds.Take(amountOfConnections - 1).Select(x => x.Key).ToList();

        if (amountOfConnections == 1)
        {
            Clients.Client(UserHandler.ConnectedIds.First().Key).hello("Send to only(also first) one");
        }
        else
        {
            Clients.Clients(allExceptLast).hello("Send to everyone except last");
            Clients.Client(lastConnection.Key).hello("Send to only the last one");
        }

        return base.OnConnected();
    }

Solution

  • Thanks for all the help (upvoted you guys). Actually found the problem.. it was inside my client. I first subscribed to the 'hello' function and after that I started the HubConnection. As soon as I changed this order everything worked fine.

    It worked with the following client code:

        private async Task ConnectToSignalR()
        {
            var hubConnection = new HubConnection("url");
            hubConnection.Headers["x-zumo-application"] = "clientapikey";
    
            IHubProxy proxy = hubConnection.CreateHubProxy("ChatHub");
    
            proxy.On<string>("hello", async (msg) =>
            {
                Console.WriteLine(msg);
            });
    
            await hubConnection.Start();
        }