SignalR - 如何从服务器上调用 Hub 方法

6

我已经成功地在ASP.NET(之前是MVC)服务器和Windows服务客户端之间使用SignalR实现了通信。客户端可以调用服务器Hub上的方法,然后将结果显示给浏览器。下面是Hub代码:

public class AlphaHub : Hub
{
    public void Hello(string message)
    {
       // We got the string from the Windows Service 
       // using SignalR. Now need to send to the clients
       Clients.All.addNewMessageToPage(message);
       // Call Windows Service
       string message1 = System.Environment.MachineName;
       Clients.All.Notify(message1);
   }
   public void CallForReport(string reportName)
   {
       Clients.All.CallForReport(reportName);
   }
}

在客户端(Windows服务)上,我一直在调用Hub上的方法:
var hubConnection = new HubConnection("http://localhost/AlphaFrontEndService/signalr",
                    useDefaultUrl: false);

IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub");
await hubConnection.Start();
string cid = hubConnection.ConnectionId.ToString();
eventLog1.WriteEntry("ConnectionID: " + cid);

// Invoke method on hub
await alphaProxy.Invoke("Hello", "Message from Service - ConnectionID: " + cid + " - " + System.Environment.MachineName.ToString() + " " + DateTime.Now.ToString());

现在,假设这个场景:用户将访问服务器上的特定ASP.NET表单,例如Insured.aspx。在那里,我想调用CallForReport,然后在客户端调用此方法:

public void CallFromReport(string reportName)
{
    eventLog1.WriteEntry(reportName);
}

我如何在服务器上连接到自己的Hub并调用方法?我尝试了从Insured.aspx执行以下操作:

protected void Page_Load(object sender, EventArgs e)
{
    // Hubs.AlphaHub.CallForReport("Insured Report");
    // IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<AlphaHub>();
    // hubContext.Clients.All.CallForReport("Insured Report");
}

当您运行最后的注释代码片段(即最后两行)时会发生什么?这是通过GetHubContext工厂获取本地实例化的hub实例的正确方法。假设hub已配置并正常工作,那么应该可以用于广播。 - Rick Strahl
1个回答

8

我没有看到任何调用IHubProxy.On的代码。这个方法是你需要使用的,它可以将你的CallFromReport方法与客户端上的AlphaHub IHubProxy连接起来。

 var hubConnection = new HubConnection("http://localhost/AlphaFrontEndService/");
 IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub");

 alphaProxy.On<string>("CallForReport", CallFromReport);

 await hubConnection.Start();

 // ...

一旦你拥有了这个,Page_Load中你已经注释的最后两行代码应该就能起作用了。
protected void Page_Load(object sender, EventArgs e)
{
    IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<AlphaHub>();
    hubContext.Clients.All.CallForReport("Insured Report");
}

完成所有操作后,我没有看到 CallFromReport 被调用。事件日志中也没有任何相关信息。 - user2471435
谢谢 @halter73,我只是漏了 await hubConnection.Start()。你刚刚帮我避免了浪费大量时间的错误。 - Jaime Yule

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接