SignalR/BlazorServer/Pages/Index.razor
2022-05-05 19:37:51 +02:00

66 lines
1.6 KiB
Plaintext

@page "/"
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager NavManager
@implements IAsyncDisposable
<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>
<hr />
<ul>
@foreach (string message in messages)
{
<li>@message</li>
}
</ul>
@code {
private HubConnection? hubConnection;
private List<string> messages = new();
private string? userInput;
private string? messageInput;
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();
}
}
}