Q:

How do you build Blazor apps with SignalR?

0

This code will help you to understand how to build Blazor apps with SignalR.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Blazor Server

In the server code, configure SignalR in the Startup.cs class file as follows.

public void ConfigureServices(IServiceCollection services)
{
    ... ... ... ...
    services.AddSignalR();
    ... ... ... ...

}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ... ... ... ...
    app.UseSignalR(routes => routes.MapHub<Blazor.NetCore.Server.SignalRHub.SignalRHub>("/signalRHub"));
    ... ... ... ...
}

And then create a SignalR hub class as follows.

   public class SignalRHub : Hub
    {
        public override Task OnConnectedAsync()
        {
            Clients.All.SendAsync("ReceiveMessage", "system", $"{Context.ConnectionId} joined the conversation");
            return base.OnConnectedAsync();
        }
        public void SendMessage(string name, string message)
        {
            Clients.All.SendAsync("ReceiveMessage", name, message);
        }

        public override Task OnDisconnectedAsync(System.Exception exception)
        {
            Clients.All.SendAsync("ReceiveMessage", "system", $"{Context.ConnectionId} left the conversation");
            return base.OnDisconnectedAsync(exception);
        }
    }

Blazor client

Create a Blazor app and add the package Blazor.Extensions.SignalR to the client. Then write the code to connect the Hub and event handler as follows.

@page "/signalr"
@using Blazor.Extensions
<div class="container">
    <input type="text" id="user" class="form-control" @bind="@userName" placeholder="User Name" /><br />
    <input type="text" id="message" class="form-control" @bind="@Message" placeholder="Message" /> <br />
    <input type="button" id="sendMessage" value="Send" class="btn btn-primary" @onclick="@SendMessage" />
    <ul id="discussion">
        @foreach (var message in messages)
        {
            <li>@message</li>
        }
    </ul>
</div>

@code {
    HubConnection connection;
    string userName = "";
    string Message = "";
    IList<string> messages = new List<string>();

    protected override async Task OnInitializedAsync()
    {
        connection = new HubConnectionBuilder().WithUrl("/signalRHub").Build();
        connection.On<string, string>("receiveMessage", this.ReceiveMessage);
        await connection.StartAsync();
    }

    Task ReceiveMessage(string name, string message)
    {
        messages.Add(name + " : " + message);
        StateHasChanged();
        return Task.CompletedTask;
    }

    async Task SendMessage()
    {
        await connection.InvokeAsync("SendMessage", userName, Message);
        Message = "";
    }
}
  1. OnInitializedAsync method, connect to the Web API.
  2. ReceiveMessage method, used in the SignalRHub class.
  3. ReceiveMessage method, concatenate the name and message parameters, and append them to a list.

The StateHasChanged method will update the bindings in the HTML. The SendMessage method will invoke the Send method in the hub with name and message parameters.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now