WPF SignalR Server

僤鯓⒐⒋嵵緔 提交于 2021-01-29 19:52:15

问题


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.

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.

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.


回答1:


You could host ASP.NET Core (including SignalR) in your WPF application.

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>

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


来源:https://stackoverflow.com/questions/60152000/wpf-signalr-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!