首页 文章

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

提问于
浏览
1

我按照this教程设法 Build 了 Client -> ServerServer -> Client 实时通信演示 . 但是,当尝试在WPF项目(而不是Console项目)中重新创建相同的场景时,我可以使用SignalR Hub中的方法 .

NOTE: WPF项目和自托管控制台项目位于 same 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
    }
}

Starting the Server & Calling the Hub method from the same Console:

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 in the WPF Project:

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 ERRORS . WPF项目's ' NotifyStation_Signup'方法永远不会被服务器调用 . 我究竟做错了什么?

2 回答

  • 0

    解决了!我通过在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

    尝试在启动集线器连接之前注册该事件 .

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

相关问题