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

标签 c# signalr

我是 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/

相关文章:

c# - 调用(委托(delegate))

azure - 为什么 Azure SignalR 函数在本地主机测试上返回 CORS 错误

signalr - 如何在 SignalR 3 中获取 HubContext?

javascript - C# Protractor AngularJS IEDriverServer Click() 异常 "Timed out waiting for page to load"

c# - 正确实现单元测试

c# - Log4Net XML 配置需要 ILoggerRepository

c# - 与 Linq DataContext 通用

c# DirectoryEntry InvokeSet HomeDirectory 和 HomeDrive,错误

c# - 使用 TeamFoundationServerFactory 进行缓慢的用户身份验证

jquery - SignalR 1.0.1 使用 Chrome 的跨域请求 (CORS)