我有一个ASP.NET(以前的MVC)服务器和Windows服务客户端之间的SignalR工作,客户端可以调用Server 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());
现在,假设这种情况:用户将在服务器上运行像Insured.aspx这样的特定ASP.NET表单。在那里我想调用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");
}
答案 0 :(得分: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");
}