SignalR - 채팅 앱 | .NET 6
dotnet new blazorserver -o ChatApp
1- qadam: Loyihaga SignalR 패키지 ni qo'shamiz.
Microsoft.AspNetCore.SignalR.Client
2- qadam: Hubs nomli Folder yaratib ichiga
ChatHub.cs
파일 오챠미즈 .Hubs/ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ChatApp.Hubs;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
3- 카담:
Program.cs
da ro'yxatdan o'tkazamiz.using ChatApp.Data;
using ChatApp.Hubs;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.ResponseCompression;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddResponseCompression(opts => {
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "application/octet-stream" });
});
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapHub<ChatHub>("/chathub");
app.MapFallbackToPage("/_Host");
app.Run();
4- qadam: 모델 폴더 yaratib uni ichida
UserMessage.cs
ochamiz.using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ChatApp.Models;
public class UserMessage
{
public string Username { get; set; }
public string Message { get; set; }
public bool CurrentUser { get; set; }
public DateTime DateSent { get; set; }
}
5- 카담:
Pages/Index.razor
ning ichidagilarni ochirib tashlaymiz va quyidagilarni yozamiz .@page "/"
@using Microsoft.AspNetCore.SignalR.Client
@using Models
@inject NavigationManager NavigationManager
@implements IAsyncDisposable
<div class="container overflow-auto shadow-sm p-3 mb-5 bg-white rounded" style="height: 500px;">
@if (!userMessages.Any())
{
<p>No messages yet, start chatting!</p>
}
@foreach (var userMessage in userMessages)
{
<div class="row mb-3 d-flex @(userMessage.CurrentUser ? "justify-content-end" : "")">
<div class="card shadow @(userMessage.CurrentUser ? "p-3 mb-2 bg-primary text-white" : "ml-5")" style="width: 18rem;">
<div class="card-header">
@(userMessage.CurrentUser ? "You" : userMessage.Username)
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item @(userMessage.CurrentUser ? "p-3 mb-2 bg-primary text-white" : "")">@userMessage.Message</li>
</ul>
<div class="card-footer">
<span class="small">@userMessage.DateSent.ToString("HH:mm | MMM dd")</span>
</div>
</div>
</div>
}
</div>
<div class="container">
<div class="row">
<div class="col-3">
<input @bind="usernameInput" type="text" class="form-control" placeholder="Your name" readonly="@isUserReadonly"/>
</div>
<div class="col-6">
<textarea @bind="messageInput" class="form-control" placeholder="Start typing..."></textarea>
</div>
<div class="col-3">
<button type="button" @onclick="Send" disabled="@(!IsConnected)" class="btn btn-primary">Send</button>
</div>
</div>
</div>
@code{
private HubConnection hubConnection;
private List<UserMessage> userMessages = new();
private string usernameInput;
private string messageInput;
private bool isUserReadonly = false;
public bool IsConnected => hubConnection.State == HubConnectionState.Connected;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
userMessages.Add(new UserMessage { Username = user, Message = message, CurrentUser = user == usernameInput, DateSent = DateTime.Now });
StateHasChanged();
});
await hubConnection.StartAsync();
}
private async Task Send()
{
if (!string.IsNullOrEmpty(usernameInput) && !string.IsNullOrEmpty(messageInput))
{
await hubConnection.SendAsync("SendMessage", usernameInput, messageInput);
isUserReadonly = true;
messageInput = string.Empty;
}
}
public async ValueTask DisposeAsync()
{
if (hubConnection is not null)
{
await hubConnection.DisposeAsync();
}
}
}
Reference
이 문제에 관하여(SignalR - 채팅 앱 | .NET 6), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/xakimov_dev/signalr-chatapp-net-6-16e9텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)