SignalR/BlazorServer/Pages/Index.razor

66 lines
1.6 KiB
Plaintext
Raw Normal View History

2022-05-05 18:48:40 +02:00
@page "/"
2022-05-05 19:37:51 +02:00
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager NavManager
@implements IAsyncDisposable
2022-05-05 18:48:40 +02:00
2022-05-05 19:37:51 +02:00
<div class="form-group">
<label>
User: <input @bind="userInput" />
</label>
</div>
<div class="form-group">
<label>
Message: <input @bind="messageInput" />
</label>
</div>
<button @onclick="Send" disabled="@(IsConnected == false)">Send</button>
2022-05-05 18:48:40 +02:00
2022-05-05 19:37:51 +02:00
<hr />
<ul>
@foreach (string message in messages)
{
<li>@message</li>
}
</ul>
2022-05-05 18:48:40 +02:00
2022-05-05 19:37:51 +02:00
@code {
private HubConnection? hubConnection;
private List<string> messages = new();
private string? userInput;
private string? messageInput;
2022-05-05 18:48:40 +02:00
2022-05-05 19:37:51 +02:00
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavManager.ToAbsoluteUri("/chathub"))
.WithAutomaticReconnect()
.Build();
hubConnection.On<string, string>("RecieveMessage", (user, message) =>
{
var formatedMessage = $"{user}: {message}";
messages.Add(formatedMessage);
InvokeAsync(StateHasChanged);
});
await hubConnection.StartAsync();
}
private async Task Send()
{
if (hubConnection != null)
{
await hubConnection.SendAsync("SendMessage", userInput, messageInput);
}
}
public bool IsConnected => hubConnection?.State == HubConnectionState.Connected;
public async ValueTask DisposeAsync()
{
if (hubConnection != null)
{
await hubConnection.DisposeAsync();
}
}
}