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

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

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

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

这是我通过Windows服务调用我的Hub的地方( 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(); context.Clients.All.addNewMessageToPage(message); } 

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

消息=远程服务器返回错误:(500)内部服务器错误。

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

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

只有当我从Web应用程序中调用集线器时,这才会起作用。

要从Web应用程序外部(例如从Windows服务)与集线器进行交互,您需要查看SignalR Client Hubs文档

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

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

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


 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)