2014-02-14 51 views
4

我有SignalR在ASP.NET(以前稱爲MVC)服務器和Windows服務客戶端之間工作,因爲客戶端可以調用服務器集線器上的方法,然後顯示瀏覽器。樞紐代碼:SignalR - 如何從服務器調用服務器上的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服務)我一直在呼籲在集線器方法:

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"); 
     } 
+0

當你運行最後一個註釋的代碼片段(最後兩行)時會發生什麼?這是通過GetHubContext工廠獲取本地實例化集線器實例的正確方法。假設集線器已經配置好並且可以工作以進行廣播。 –

回答

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"); 
} 
+0

做完所有這些後,我沒有看到CallFromReport調用。事件日誌中沒有任何內容。 – user2471435

+0

對不起,它的工作! – user2471435

+0

謝謝@ halter73剛剛缺少'await hubCoonection.Start()'。你只是把我從很大的時間浪費了。 –

相關問題