SignalR-从自托管控制台服务器调用WPF客户端方法
本文关键字:调用 WPF 客户端 方法 服务器 控制台 SignalR- | 更新日期: 2023-09-27 17:58:25
我遵循了本教程,并成功地设置了Client->Server和Server->Client实时通信演示。然而,当试图在WPF项目(而不是控制台项目)中重新创建相同的场景时,我似乎无法从SignalR Hub调用WPF项目的方法。
注意: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
}
}
启动服务器&从同一控制台调用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"方法从未被服务器调用。我做错了什么?
解决了它!我犯了一个愚蠢的错误,在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();
}
}
尝试在启动集线器连接之前注册事件。
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();