c# - 无法在 SignalR 与 WPF 客户端之间建立连接
问题描述
我在带有 SignalR(JavaScript 客户端)的 ASP.NET Core 中有一个 WEB API 应用程序。这是我的启动配置:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
....................................
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
policy => policy.WithOrigins(Configuration.GetSection("ApplicationPortalURL").Value)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
............................................
services.AddSingleton<MyHub>();
services.AddSignalR();
............................................
services.AddMvc();
.AddControllersAsServices()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var builder = new ContainerBuilder();
builder.Populate(services);
ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);
}
public async void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<MyHub>("/MyHub");
});
app.UseMvc();
var bus = ApplicationContainer.Resolve<IBusControl>();
await Task.Run(() =>
{
var busHandle = TaskUtil.Await(() => bus.StartAsync());
lifetime.ApplicationStopping.Register(() => busHandle.Stop());
});
}
集线器类
public class MyHub : Hub
{
public static HashSet<string> CurrentConnections = new HashSet<string>();
public async override Task OnConnectedAsync()
{
await base.OnConnectedAsync();
}
public async override Task OnDisconnectedAsync(Exception exception)
{
await base.OnDisconnectedAsync(exception);
}
public async Task SendMessage(string message)
{
await Clients.All.SendAsync("sendmessage", message);
}
}
Javascript
const connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:33300/MyHub", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
}).build();
connection.on("sendmessage", (message) => {
debugger;
altert(message);
});
connection.start().then(function (client) {
console.log('Signal r connection started.');
console.log(client);
}).catch(function (err) {
return console.error(err);
});
网站部分一切正常。但我也有一个 WPF 客户端。
WPF 客户端
namespace WpfAppSignalRClient
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitializeSignalR();
}
private void InitializeSignalR()
{
try
{
var hubConnection = new HubConnection("http://localhost:33300/");
var prestoHubProxy = hubConnection.CreateHubProxy("MyHub");
prestoHubProxy.On<string>("sendmessage", (message) =>
{
MessageBox.Show(message);
});
hubConnection.Start();
}
catch (System.Exception ex)
{
throw ex;
}
}
}
}
我想将 SignalR 消息从 web api 推送到 WPF。我的意思是我希望消息出现在 WPF 中的同时消息显示在网页中。现在 SignalR 消息只显示在网站中,它没有显示在 WPF 应用程序中。
解决方案
我根据用户@mm8 的评论发布了这个答案。
我在我的 WPF 应用程序部分做了一些更改。首先我Microsoft.AspNetCore.SignalR.Client
从nuget添加。然后更改 SignalR 连接代码,如下所示。
private async void InitializeSignalR()
{
try
{
connection = new HubConnectionBuilder()
.WithUrl("http://localhost:33300/MyHub")
.Build();
#region snippet_ClosedRestart
connection.Closed += async (error) =>
{
await Task.Delay(new Random().Next(0, 5) * 1000);
await connection.StartAsync();
};
#endregion
#region snippet_ConnectionOn
connection.On<string>("sendmessage", (message) =>
{
this.Dispatcher.Invoke(() =>
{
lstListBox.Items.Add(message);
});
});
#endregion
try
{
await connection.StartAsync();
lstListBox.Items.Add("Connection started");
//connectButton.IsEnabled = false;
btnSend.IsEnabled = true;
}
catch (Exception ex)
{
lstListBox.Items.Add(ex.Message);
}
}
catch (System.Exception ex)
{
throw ex;
}
}
现在它工作正常。
推荐阅读
- c++ - 如何将数组的地址分配给指针?
- python-3.x - 使用 panda python 的样本数 -5 必须为非负数
- selenium - 使用 Selenium Grid 进行数据驱动测试
- macos - 无法通过 macOS 中的 ansible unarchive 模块提取 tar 文件?
- xpath - 如何为以下代码编写 XML 路径表达式?
- image - Ionic Framework 的光学字符识别插件
- angular - Angular Material 固定侧栏标题不是固定的
- c++ - C ++ 2d数组用文件中的最后一个元素值填充所有元素
- node.js - 想用 Nodejs 每 N 秒发出一次“X Post”请求(我正在使用 facebook 聊天机器人,所以我想每秒发出 250 个 Post 请求)
- reactjs - 为什么即使更新了商店,redux mapStateToProps 也不更新组件道具?