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

时间:2017-10-10 18:28:26

标签: asp.net-core-signalr

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

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

3 个答案:

答案 0 :(得分:2)

步骤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);
    }
}

第2步:

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSingleton<ErrorService>();
        ...
    }

第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();
    }
....

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

public class TestService
{
    public TestService(..., ErrorService errorService)
    {
        string ConnectionId = ...;
        errorService.KickClient(ConnectionId);

答案 1 :(得分:-1)

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

答案 2 :(得分:-2)