【发布时间】:2014-02-14 19:59:53
【问题描述】:
我有 SignalR 在 ASP.NET(以前称为 MVC)服务器和 Windows 服务客户端之间工作,因为客户端可以调用服务器集线器上的方法,然后显示给浏览器。集线器代码是:
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);
}
如何在服务器上连接到我自己的集线器并调用该方法。我尝试了 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");
}
【问题讨论】:
-
当您运行最后一个注释代码 sn-p(即最后两行)时会发生什么?这是通过 GetHubContext 工厂获取本地实例化集线器实例的正确方法。假设集线器已配置并正在工作,应该可以进行广播。