80 lines
2.2 KiB
Plaintext
80 lines
2.2 KiB
Plaintext
@page "/{room}"
|
|
@using Microsoft.AspNetCore.SignalR.Client
|
|
@using spanreed.Shared
|
|
@inject NavigationManager NavigationManager
|
|
@implements IDisposable
|
|
@inject HttpClient Http
|
|
|
|
<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)">Send</button>
|
|
|
|
<hr>
|
|
|
|
<ul id="messagesList">
|
|
@foreach (var message in messages)
|
|
{
|
|
<li><MessageComponent author=@message.Author content=@message.Content timestamp=@message.Timestamp /></li>
|
|
}
|
|
</ul>
|
|
|
|
@code {
|
|
private HubConnection hubConnection;
|
|
private List<ChatData> messages = new List<ChatData>();
|
|
private string userInput;
|
|
private string messageInput;
|
|
[Parameter]
|
|
public string room {get; set;}
|
|
|
|
protected override async Task OnParametersSetAsync() {
|
|
if (hubConnection != null) {
|
|
try {
|
|
await hubConnection.StopAsync();
|
|
}
|
|
finally {
|
|
await hubConnection.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
messages.Clear();
|
|
messageInput = "";
|
|
|
|
hubConnection = new HubConnectionBuilder().WithUrl(NavigationManager.ToAbsoluteUri("/sendmessage")).Build();
|
|
hubConnection.On<string, string, DateTime>("Received", (author, content, timestamp) => {
|
|
messages.Add(new ChatData{Author = author, Content = content, Timestamp = timestamp});
|
|
StateHasChanged();
|
|
});
|
|
var old_messages = await Http.GetFromJsonAsync<ChatData[]>($"Chat/{room}");
|
|
|
|
if (old_messages != null) {
|
|
foreach (var message in old_messages)
|
|
{
|
|
messages.Add(message);
|
|
}
|
|
}
|
|
|
|
await hubConnection.StartAsync();
|
|
|
|
await hubConnection.SendAsync("Connect", room);
|
|
}
|
|
|
|
Task Send() =>
|
|
hubConnection.SendAsync("sendMessage", userInput, messageInput, room, DateTime.Now);
|
|
|
|
public bool IsConnected =>
|
|
hubConnection.State == HubConnectionState.Connected;
|
|
|
|
public void Dispose() {
|
|
_ = hubConnection.DisposeAsync();
|
|
}
|
|
} |