Search code examples
c#asp.net-coresignalrasp.net-core-signalr

SignalR Client won't print the Queue Position


I have the Following Code for my SignalR Client. Based on my knowledge so far, this code should print anything that is send by "noitfyQueuePosition" event.

using Microsoft.AspNetCore.SignalR.Client;

Console.WriteLine("Connecting to Hub...");

var hubConnection = new HubConnectionBuilder().WithUrl("https://localhost:7178/queueHub").Build();

hubConnection.Closed += async (error) =>
{
    Console.WriteLine("Connection closed. Reconnecting...");
    await Task.Delay(new Random().Next(0, 5) * 1000);
    await hubConnection.StartAsync();
};

hubConnection.On<string>("notifyQueuePosition", (queueCount) =>
{
    Console.WriteLine($"Message received from server: {queueCount}");
});

try
{
    await hubConnection.StartAsync();
    Console.WriteLine("Connected to SignalR Hub.");

    await hubConnection.InvokeAsync("JoinQueue", "fj294ij29r8jv09258jwr0fj2508f2trvjh2");
}
catch (Exception ex)
{
    Console.WriteLine($"Error connecting to SignalR Hub: {ex.Message}");
}

Console.ReadLine();

I'm using an instance of my hub in another class and using the following method to send queue count to every connection in my server. "await _queueHub.Clients.All.SendAsync("notifyQueuePosition", queueCount);"

The problem is that Queue Count isn't getting printed on my Client's Console.


Solution

  • I create a background service and reproduced your issue, and I get the error like below. The error maybe same as your side, if not, please check the Suggestion below, it my help you to print the more details like my picture.

    enter image description here

    Then I add the Newtonsoft.Json package and format the data, then fix the issue.

    Like below

    public Task AddToQueue(string userToken)
    {
        _queueManager.JoinQueue(userToken, Context.ConnectionId);
        // using JsonConvert.SerializeObject to format the data
        Clients.All.SendAsync("notifyQueuePosition", JsonConvert.SerializeObject(1));
        return Task.CompletedTask;
    }
    
    // the method inside my test service
    private void OnNotifyQueuePositionHandler(string queueCount)
    {
        var data = JsonConvert.DeserializeObject(queueCount);
        Console.WriteLine($"Message received from server: {queueCount}");
    }
    

    Here is my full code.

    using WebApplication2.IServices;
    using Microsoft.AspNetCore.SignalR.Client;
    using Newtonsoft.Json;
    
    namespace WebApplication2.BackgroundServices
    {
        public class HubClientService : BackgroundService
        {
            private readonly IQueueManager _queueManager;
    
            public HubClientService(IQueueManager queueManager)
            {
                _queueManager = queueManager;
            }
    
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    //Console.WriteLine(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + $"   The number of members in the queue: {_queueManager?.UserQueue?.Count}");
                    //await Task.Delay(5000, stoppingToken);
                    Console.WriteLine("Connecting to Hub...");
    
                    var hubConnection = new HubConnectionBuilder().WithUrl("https://localhost:7245/queueHub").ConfigureLogging(logging =>
                    {
                        // Log to the Console
                        logging.AddConsole();
    
                        // This will set ALL logging to Debug level
                        logging.SetMinimumLevel(LogLevel.Debug);
                    }).Build();
    
                    hubConnection.Closed += async (error) =>
                    {
                        Console.WriteLine("Connection closed. Reconnecting...");
                        await Task.Delay(new Random().Next(0, 5) * 1000);
                        await hubConnection.StartAsync();
                    };
    
                    //hubConnection.On<string>("notifyQueuePosition", (queueCount) =>
                    //{
                    //  Console.WriteLine($"Message received from server: {queueCount}");
                    //});
    
                    hubConnection.On<string>("notifyQueuePosition", OnNotifyQueuePositionHandler);
    
    
                    try
                    {
                        await hubConnection.StartAsync();
                        Console.WriteLine("Connected to SignalR Hub.");
    
                        await hubConnection.InvokeAsync("AddToQueue", "fj294ij29r8jv09258jwr0fj2508f2trvjh2");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error connecting to SignalR Hub: {ex.Message}");
                    }
    
                    await Task.Delay(5000, stoppingToken);
                }
            }
            public Func<string, Task>? NotifyQueuePositionHandler { get; set; }
            private void OnNotifyQueuePositionHandler(string queueCount)  
            {
                var data = JsonConvert.DeserializeObject(queueCount);
                Console.WriteLine($"Message received from server: {queueCount}");
            }
        }
    }
    

    Success Picture

    enter image description here

    Suggestion

    We need to enable the signalr client logging to check the detailed message.

    var connection = new HubConnectionBuilder()
    .WithUrl("https://example.com/my/hub/url")
    .ConfigureLogging(logging =>
    {
        // Log to the Console
        logging.AddConsole();
    
        // This will set ALL logging to Debug level
        logging.SetMinimumLevel(LogLevel.Debug);
    })
    .Build();