2016-07-22 60 views
1

一個WPF客戶端方法,我也跟着this教程和管理,以建立一個客戶端 - >服務器服務器 - >客戶端實時通信演示。但是,當試圖在WPF項目(而不是控制檯項目)中重新創建相同的場景時,我似乎無法從SignalR Hub調用WPF項目的方法。SignalR - 調用從自託管控制檯服務器

注:的WPF項目和自託管控制檯項目都在相同 Visual Studio解決方案

SignalR樞紐:(在自主機服務器控制檯項目)

public class TestHub : Hub 
{ 
    public void NotifyAdmin_Signup() 
    { 
     Clients.All.NotifyStation_Signup(); 
     //This should call the WPF Project's NotifyStation_Signup() method 
    } 
} 

啓動服務器&從同一個控制檯調用集線器方法:

class Program 
{ 
    static void Main(string[] args) 
    { 
     //Start the Local server 
     string url = @"http://localhost:8080/"; 
     using (WebApp.Start<Startup>(url)) 
     { 
      Console.WriteLine(string.Format("Server running at {0}", url)); 
      Console.ReadLine(); 
     } 

     IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<TestHub>(); 
     hubContext.Clients.All.NotifyAdmin_Signup(); 
    } 
} 

MainWindow.xaml.cs在WPF項目:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     var hubConnection = new HubConnection("http://localhost:8080/"); 
     IHubProxy _hub = hubConnection.CreateHubProxy("TestHub"); 
     hubConnection.Start().Wait(); 

     //Call a local method when the Server sends a signal 
     _hub.On("NotifyStation_Signup", x => PrintAccountCount()); 
    } 

    //This never gets called :(
    private void PrintAccountCount() 
    { 
     //Display a Message in the Window UI 
     var dispatcher = Application.Current.Dispatcher; 
     dispatcher.Invoke(() => counter_accounts.Content = "I got the signal!"); 
    } 
} 

NO錯誤。 WPF項目的'NotifyStation_Signup'方法永遠不會被服務器調用。我究竟做錯了什麼?

回答

0

嘗試註冊事件之前您啓動集線器連接。

 var hubConnection = new HubConnection("http://localhost:8080/"); 
    IHubProxy _hub = hubConnection.CreateHubProxy("TestHub"); 

    //Call a local method when the Server sends a signal 
    _hub.On("NotifyStation_Signup", x => PrintAccountCount()); 

    hubConnection.Start().Wait(); 
+0

相同的結果。不會被叫做兄弟 – Dinuka

1

解決了!我通過調用using()方法之外的集線器方法犯了一個愚蠢的錯誤:

static void Main(string[] args) 
{ 
    //Start the Local server 
    string url = @"http://localhost:8080/"; 
    using (WebApp.Start<Startup>(url)) 
    { 
     Console.WriteLine(string.Format("Server running at {0}", url)); 
     //Instead of having the following two lines outside of this, 
     //I put it in here and it worked :) 
     IHubContext hubContext = 
       GlobalHost.ConnectionManager.GetHubContext<TestHub>(); 
     hubContext.Clients.All.NotifyAdmin_Signup(); 
     Console.ReadLine(); 
    } 
}