断开客户端与 IHubContext<THub> 的连接

Car*_*ler 5 asp.net-core-signalr

我可以使用 IHubContext 接口从服务器代码调用 InvokeAsync,但有时我想强制这些客户端断开连接。

那么,有没有办法将客户端与引用 IHubContext 接口的服务器代码断开连接?

Pet*_*sky 6

第1步:

using Microsoft.AspNetCore.Connections.Features;
using System.Collections.Generic;
using Microsoft.AspNetCore.SignalR;

public class ErrorService
{
    readonly HashSet<string> PendingConnections = new HashSet<string>();
    readonly object PendingConnectionsLock = new object();

    public void KickClient(string ConnectionId)
    {
        //TODO: log
        if (!PendingConnections.Contains(ConnectionId))
        {
            lock (PendingConnectionsLock)
            {
                PendingConnections.Add(ConnectionId);
            }
        }
    }

    public void InitConnectionMonitoring(HubCallerContext Context)
    {
        var feature = Context.Features.Get<IConnectionHeartbeatFeature>();

        feature.OnHeartbeat(state =>
        {
            if (PendingConnections.Contains(Context.ConnectionId))
            {
                Context.Abort();
                lock (PendingConnectionsLock)
                {
                    PendingConnections.Remove(Context.ConnectionId);
                }
            }

        }, Context.ConnectionId);
    }
}
Run Code Online (Sandbox Code Playgroud)

第2步:

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSingleton<ErrorService>();
        ...
    }
Run Code Online (Sandbox Code Playgroud)

第 3 步:

[Authorize(Policy = "Client")]
public class ClientHub : Hub
{
    ErrorService errorService;

    public ClientHub(ErrorService errorService)
    {
        this.errorService = errorService;
    }

    public async override Task OnConnectedAsync()
    {
        errorService.InitConnectionMonitoring(Context);
        await base.OnConnectedAsync();
    }
....
Run Code Online (Sandbox Code Playgroud)

不使用 Abort() 方法断开连接:

public class TestService
{
    public TestService(..., ErrorService errorService)
    {
        string ConnectionId = ...;
        errorService.KickClient(ConnectionId);
Run Code Online (Sandbox Code Playgroud)


Paw*_*wel 0

在 alpha 2 中,您可以使用Abort()onHubConnectionContext来终止连接。然而,我没有看到从中心外部访问它的简单方法。因为您控制客户端,所以您只需调用客户端方法并告诉客户端断开连接。优点是客户端可以优雅地断开连接。缺点是需要将消息发送到客户端,而不是仅在服务器端断开客户端连接。