gpt4 book ai didi

c# - SignalR Hub 上下文中没有可用的客户端

转载 作者:行者123 更新时间:2023-11-30 12:46:30 26 4
gpt4 key购买 nike

我是 SignalR 的新手,正在尝试设置可用于将事件发送到其他应用程序的自托管服务。我在获取要在所有客户端上调用的方法时遇到问题。在下面的代码中,_context.Clients.All 始终为空。有什么想法吗?

测试方法:

var server = new SignalRServer();
server.Start("http://localhost:8555");
var hubConnection = new HubConnection("http://localhost:8555");
var proxy = hubConnection.CreateHubProxy("testHub");
var executed = false;
proxy.On("testMethod", () =>
{
executed = true;
});
hubConnection.Start().Wait();
var hub = new TestHubContext(GlobalHost.ConnectionManager.GetHubContext<TestHub>());
hub.Test();
hubConnection.Stop();
server.Stop();

自托管服务器:

public class SignalRServer
{
private IDisposable _signalR;

public void Start(string url)
{
_signalR = WebApp.Start<SignalRStartup>(url);
}

public void Stop()
{
_signalR.Dispose();
}
}

public class SignalRStartup
{
public static IAppBuilder App = null;

public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}

中心:

public class TestHub : Hub
{

}

public class TestHubContext
{
private IHubContext _context;


public TestHubContext(IHubContext context)
{
_context = context;
}


public void Test()
{
if (_context != null)
{
// At this poing _context.Clients.All is always empty
_context.Clients.All.testMethod();
}
}
}

最佳答案

我认为您的上下文/客户端连接很好。在没有进一步信息的情况下,我猜你的问题是你在调用 hub.Test() 之后关闭连接和服务器的速度太快

注释掉两个 .Stop() 调用(并在其中粘贴 Console.ReadLine 以保持控制台打开)并查看会发生什么

关于c# - SignalR Hub 上下文中没有可用的客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19916405/

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