[英]signalR calls a server method and that method calls a callback method ,outside the hub. How can I call client function from that method?
[英]SignalR - How can I call Hub Method on server from server
我有一個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");
}
我沒有看到任何對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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.