WPF SignalR 服务器 [英] WPF SignalR Server
问题描述
我真的被困住了,需要一些帮助.我有一个 .NET Core 3.1 WPF 应用程序,它解码篮球记分牌数据,现在我需要将此数据发送到 .html 文件..html 文件作为模板通过 CasparCG 服务器打开一次,需要以某种方式使其数据实时更新.
I'm really stuck and need some help. I have a .NET Core 3.1 WPF application, which decodes basketball scoreboard data and now I need to send this data over to .html file. The .html file is opened once through CasparCG server as a template and needs to somehow have it's data update real-time.
我目前认为最好的方法是在 WPF 应用程序中有一个 SignalR 服务器和一个运行 SignalR 客户端的 html 模板.其中一项要求是我必须能够通过单击按钮启动和停止 SignalR 服务器.
I currently thinking that the best way to do this is to have a SignalR server in the WPF app and a html template running a SignalR client. One of the requirements is that I have to be able to start and stop the SignalR server with a button click.
问题是,我完全不知道从哪里开始,因为关于在 WPF 应用程序上托管 SignalR 服务器的信息似乎很少.
The problem is, I have absolutely no idea where to start as it seems that there's very little information regarding hosting a SignalR server on WPF app.
推荐答案
您可以在 WPF 应用程序中托管 ASP.NET Core(包括 SignalR).
You could host ASP.NET Core (including SignalR) in your WPF application.
在 .csproj
文件中引用 Microsoft.AspNetCore.App
NuGet 包作为框架引用:
Reference the Microsoft.AspNetCore.App
NuGet package as a framework reference in your .csproj
file:
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" Version="2.2.8" />
</ItemGroup>
使用 Host.CreateDefaultBuilder
API 创建一个 IHost
并在单击按钮时根据需要启动和停止它:
Create an IHost
using the Host.CreateDefaultBuilder
API and start it and stop it as required when your buttons are clicked:
using System.Windows;
using System.ComponentModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private IHost _host;
private async void Start_Click(object sender, RoutedEventArgs e)
{
_host?.Dispose();
_host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder => webBuilder
.UseUrls("http://localhost:5100")
.ConfigureServices(services => services.AddSignalR())
.Configure(app =>
{
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapHub<StreamHub>("/streamHub"));
}))
.Build();
await _host.StartAsync();
}
private async void Stop_Click(object sender, RoutedEventArgs e)
{
if (_host != null)
{
await _host.StopAsync();
_host.Dispose();
}
}
protected override void OnClosing(CancelEventArgs e)
{
_host?.Dispose();
base.OnClosing(e);
}
}
}
这篇关于WPF SignalR 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!