我已经成功地在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");
}