首页 文章

SignalR - 从集线器外部通过另一个项目中的集线器进行广播

提问于
浏览
7

我的解决方案中有两个项目:

项目1:“SignalRChat”(MVC) - 工作正常项目2:“DatabaseWatcherService”Windows服务 - 正常工作

我正试图从我的Windows服务中调用SignalRChat Hub,但它似乎没有工作 .

这是我从我的Windows服务(https://github.com/SignalR/SignalR/wiki/Hubs#broadcasting-over-a-hub-from-outside-of-a-hub)调用我的集线器的地方:

void PerformTimerOperation(object sender, EventArgs e)
    {
        eventLog1.WriteEntry("Timer ticked...");

        var message = "test";

        var context = GlobalHost.ConnectionManager.GetHubContext<SignalRChat.ChatHub>();
        context.Clients.All.addNewMessageToPage(message);
    }

尝试连接时出现以下错误:

Message =远程服务器返回错误:(500)内部服务器错误 .

我正在尝试通过 var connection = new HubConnection("http://localhost:2129"); 进行连接

端口2129是我运行的MVC项目 .

1 回答

  • 16

    只有当我从Web应用程序中调用集线器时,这才有效 .

    为了从Web应用程序外部与集线器进行交互,例如,从Windows服务,你需要看一下SignalR Client Hubs documentation

    • 将以下NuGet包添加到项目中: Microsoft.AspNet.SignalR.Client

    • 将以下语句添加到页面顶部: using Microsoft.AspNet.SignalR.Client;

    • 您需要创建与集线器的连接,然后启动连接 .


    var connection = new HubConnection("http://mysite/");
    IHubProxy myHub = connection.CreateHubProxy("MyHub");
    
    connection.Start().Wait(); // not sure if you need this if you are simply posting to the hub
    
    myHub.Invoke("addNewMessageToPage", "Hello World");
    

    在你的集线器中,你需要有一个 AddNewMessageToPage 的方法,它接受hello world字符串并从这里调用 Clients.All.addNewMessageTopage(message)

相关问题