Ragesh Puthiyedath Raju
Ragesh Puthiyedath Raju

Reputation: 3939

Can't establish the connection between SignalR with WPF Client

I have a WEB API application in ASP.NET Core with SignalR (JavaScript Client). Here is my startup configuration:

    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 Class

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

Everything works fine in the website part. But I have a WPF Client too.

WPF Client

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

I want to push SignalR message from web api to WPF. I mean I expect the message appear in the WPF at the same time the message shows in the web page. Now the SignalR messages only shows in the website, it's not showing in the WPF application.

Upvotes: 1

Views: 3085

Answers (1)

Ragesh Puthiyedath Raju
Ragesh Puthiyedath Raju

Reputation: 3939

I posted this answer as per the comments by user @mm8.

I have do some changes in my WPF application section. First I added Microsoft.AspNetCore.SignalR.Client from nuget. Then change the SignalR connection code as shown below.

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

Now it works fine.

Upvotes: 1

Related Questions