2

Below is my SignalR Hub class code.

public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Call the addNewMessageToPage method to update clients.
        Clients.All.addNewMessageToPage(name, message);
    }


    public async void webAPIRequest()
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts");
        //Clients.All.addWebAPIResponseToPage(response);
        Clients.Caller.addWebAPIResponseToPage(response);

        await Task.Delay(1000);

        response = await client.GetAsync("http://www.google.com");

        Clients.Caller.addWebAPIResponseToPage(response);
        //Clients.All.addWebAPIResponseToPage(response);

        await Task.Delay(1000);

        response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts?userId=1");
        //Clients.All.addWebAPIResponseToPage(response);
        Clients.Caller.addWebAPIResponseToPage(response);

    }

}

As per my understanding ,

Clients.Caller.addWebAPIResponseToPage(response);

sends message only to caller client , whereas

Clients.All.addWebAPIResponseToPage(response);

sends the message to all the clients.

  1. Is my understanding correct ?

  2. If No , then what method needs to be called to send message only to caller client.

2 Answers 2

6

Yes your understanding is correct. Read it here https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-server#selectingclients

You can use caller, you can provide current user connection id and send message to that or I have seen a group called self in some places which keeps user logged in from various devices and send message to that.

For example if you are logged in on a desktop and on mobile as well then you will have two connection IDs but you are same user. You can add this user to a self_username_unique_group_name kind of group and then send a message to that group which will be sent to all devices where user is connected.

You can also manage connection IDs for a single user in a separate table and send message to all of those connection IDs if you want.

Too much flexibility and magic Enjoy

0

I found this to work quite well where ConnectionMapping is described in https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddScoped<SomeService>();
        services.AddScoped<SessionService>();
        services.AddScoped<ProgressHub>();
    }
}

public class SomeService 
{
    ProgressHub _hub;

    public SomeService(ProgressHub hub)
    {
        _hub = hub;
    }

    private async Task UpdateProgressT(T value)
    {
        _hub.Send(value);
    }
}



public class ProgressHub : Hub
{
    private readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>();
    private readonly IHubContext<ProgressHub> _context;
    private readonly SessionService _session;

    public ProgressHub(IHubContext<ProgressHub> context, SessionService session)
    {
        _context = context;
        _session = session;
    }

    public override Task OnConnectedAsync()
    {            
        _connections.Add(_session.SiteId, Context.ConnectionId);

        return base.OnConnectedAsync();
    }

    public override Task OnDisconnectedAsync(Exception exception)
    {            
        _connections.Remove(_session.SiteId, Context.ConnectionId);

        return base.OnDisconnectedAsync(exception);
    }        
        
    public async Task Send(object data)
    {            
        foreach (var connectionId in _connections.GetConnections(_session.SiteId))
        {
            await _context.Clients.Client(connectionId).SendAsync("Message", data);
        }
    }
}


public class SessionService
{
    private readonly ISession _session;

    public SessionService(IHttpContextAccessor accessor)
    {
        _session = accessor.HttpContext.Session;

        if (_session == null) throw new ArgumentNullException("session");
    }   

    public string SiteId
    {
        get => _session.GetString("SiteId");
        set => _session.SetString("SiteId", value);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.