如何向SignalR中的调用方客户端发送消息?

时间:2017-06-16 11:36:35

标签: signalr

以下是我的SignalR Hub类代码。

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);

    }

}

根据我的理解,

Clients.Caller.addWebAPIResponseToPage(response);

仅向呼叫者客户端发送消息,而

Clients.All.addWebAPIResponseToPage(响应);

将消息发送给所有客户端。

  1. 我的理解是否正确?

  2. 如果否,那么需要调用什么方法才能将消息发送给调用者客户端。

2 个答案:

答案 0 :(得分:3)

是的,你的理解是正确的。在这里阅读 https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-server#selectingclients

您可以使用来电,您可以提供当前的用户连接ID并向其发送消息,或者我在某些地方看到过一个名为self的组,该组保持用户从各种设备登录并向其发送消息。

例如,如果您在桌面和移动设备上登录,那么您将拥有两个连接ID,但您是同一个用户。您可以将此用户添加到self_username_unique_group_name类别的组中,然后向该组发送一条消息,该消息将发送到用户所连接的所有设备。

您还可以在单​​独的表中管理单个用户的连接ID,并根据需要向所有这些连接ID发送消息。

太多的灵活性和魔力 享受

答案 1 :(得分:0)

https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections

中描述了ConnectionMapping的地方,我发现这很好用
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);
    }
}
相关问题