【问题标题】:Can't establish the connection between SignalR with WPF Client无法在 SignalR 与 WPF 客户端之间建立连接
【发布时间】:2020-05-13 18:35:25
【问题描述】:

我在带有 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());
        });
    }

HUB 类

 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 应用程序中。

【问题讨论】:

  • 您使用的是哪个 NuGet 包?您应该使用 Microsoft.AspNetCore.SignalR.Client 连接到 ASP.NET Core SignalR 集线器。 GitHub 上有一个example
  • @mm8 你是对的! OP 可证明使用 @aspnet/signlar 作为 javascript 客户端。 WPF 客户端需要 Signlar.Client 包。
  • @mm8 非常感谢您的正确建议。我将在 WPF 部分发布我所做更改的答案。

标签: c# .net wpf asp.net-core signalr


【解决方案1】:

我根据用户 @mm8 的 cmets 发布了这个答案。

我对我的 WPF 应用程序部分进行了一些更改。首先,我从 nuget 添加了Microsoft.AspNetCore.SignalR.Client。然后如下图更改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;
        }
    }

现在它工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多