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

标签 c# signalr signalr-hub

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

Project 1: "SignalRChat" (MVC) - Works fine
Project 2: "DatabaseWatcherService" Windows Service - Works fine

我正在尝试从我的 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=The remote server returned an error: (500) Internal Server Error.

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

进行连接

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

最佳答案

据我所知,这仅在您从 Web 应用程序中调用集线器时有效。

为了从网络应用程序外部与中心交互,例如从 Windows 服务,您需要查看 SignalR Client Hubs documentation

  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)

关于c# - SignalR - 从集线器外部通过另一个项目中的集线器广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16170373/

相关文章:

javascript - 通过使用 $resource 从 Angular ​​调用 c# webservice 来设置 Controller 变量

c# - SignalR 差异

signalr - 可以在服务器端检测到 SignalR 消息丢失吗?

SignalR集线器过载

c# - 这是什么编码 : <ESC>[00p<ESC>(1*259*01/26/10*11. 05*<CR>

C# 等效于 PHP http_build_query

c# - SignalR disconnect 在互联网断开/重新连接时未被调用

c# - SignalR 函数返回值

c# - 如何将 JValue 转换为 bool?

c# - 在 Controller (ASP.NET Core)中进行 DI 时如何在 SignalR 中使用 Clients.Caller 和 Clients.Others?