SignalR - 从自托管控制台服务器调用WPF客户端方法

时间:2016-07-22 14:35:46

标签: c# wpf signalr signalr-hub signalr.client

我按照this教程设法设置了客户端 - >服务器服务器 - >客户端实时通信演示。但是,当尝试在WPF项目(而不是Console项目)中重新创建相同的场景时,我似乎无法从SignalR Hub调用WPF项目的方法。

注意: WPF项目和自托管控制台项目位于相同 Visual Studio解决方案

SignalR Hub:(在自主服务器控制台项目中)

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

启动服务器&从同一控制台调用Hub方法:

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();
    }
}

WPF项目中的MainWindow.xaml.cs:

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

无错误。 WPF项目的NotifyStation_Signup&#39;方法永远不会被服务器调用。我做错了什么?

2 个答案:

答案 0 :(得分:1)

解决了!我通过在using()方法之外调用hub方法犯了一个愚蠢的错误:

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();
    }
}

答案 1 :(得分: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();