gpt4 book ai didi

asp.net-core-signalr - 断开客户端与 IHubContext 的连接

转载 作者:行者123 更新时间:2023-12-01 19:16:39 26 4
gpt4 key购买 nike

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

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

最佳答案

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

关于asp.net-core-signalr - 断开客户端与 IHubContext<THub> 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46673526/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com