[] SignalR을 활용한 채팅서비스(기초) 개발 및 테스트

This commit is contained in:
Seonkyu_Kim 2025-02-17 15:35:58 +09:00
parent a8e2a63db0
commit e48eb6f76b
2 changed files with 69 additions and 10 deletions

View File

@ -1,12 +1,10 @@
using Pomelo.EntityFrameworkCore;
using System.Text;
using AcaMate.Common.Chat;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.SignalR;
using AcaMate.Common.Models;
using AcaMate.V1.Services;
using AcaMate.Common.Data;
@ -15,9 +13,6 @@ using AcaMate.V1.Controllers;
var builder = WebApplication.CreateBuilder(args);
// DB 설정부 시작
builder.Configuration.AddJsonFile("private/dbSetting.json", optional: true, reloadOnChange: true);
// var connectionString = builder.Configuration.GetConnectionString("MariaDbConnection");
@ -31,7 +26,7 @@ builder.Services.AddDbContext<AppDbContext>(optionsAction: (serviceProvider, opt
{
baseConnectionString = baseConnectionString.Replace("database=AcaMate", $"database={dbName}");
}
options.UseMySql(baseConnectionString, ServerVersion.AutoDetect(baseConnectionString));
});
builder.Services.AddHttpContextAccessor();
@ -53,7 +48,8 @@ builder.Services.AddAuthentication(options =>
.AddJwtBearer(options =>
{
var jwtSettings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
options.TokenValidationParameters = new TokenValidationParameters {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
@ -76,6 +72,23 @@ builder.Services.AddEndpointsApiExplorer();
// builder.Services.AddSwaggerGen();
builder.Services.AddCustomSwagger();
// SignalR 설정 추가 부분
builder.Services.AddSignalR();
builder.Services.AddCors(option =>
{
option.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.SetIsOriginAllowed(host => true);
});
});
///// ===== builder 설정 부 ===== /////
var app = builder.Build();
if (app.Environment.IsDevelopment())
@ -84,7 +97,6 @@ if (app.Environment.IsDevelopment())
// app.UseSwaggerUI();
app.UseCustomSwaggerUI();
app.UseDeveloperExceptionPage(); // 좀더 자세한 예외 정보 제공
}
else
{
@ -98,4 +110,14 @@ app.UseAuthorization();
app.MapControllers();
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseWebSockets();
app.UseEndpoints(end =>
{
app.MapHub<ChatHub>("/chatHub");
});
app.Run();

View File

@ -0,0 +1,37 @@
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace AcaMate.Common.Chat;
public class ChatHub : Hub
{
// 클라이언트에서 메시지를 보내면 모든 사용자에게 전송
public async Task SendMessage(string user, string message)
{
Console.WriteLine($"Message received: {user}: {message}");
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
// 특정 사용자에게 메시지를 보냄
public async Task SendMessageToUser(string connectionId, string message)
{
await Clients.Client(connectionId).SendAsync("ReceiveMessage", message);
}
// 클라이언트가 연결될 때 호출
public override async Task OnConnectedAsync()
{
await Clients.Caller.SendAsync("ReceiveMessage", "System", $"Welcome! Your ID: {Context.ConnectionId}");
Console.WriteLine("OnConnectedAsync");
await base.OnConnectedAsync();
}
// 클라이언트가 연결 해제될 때 호출
public override async Task OnDisconnectedAsync(Exception? exception)
{
await Clients.All.SendAsync("ReceiveMessage", "System", $"{Context.ConnectionId} disconnected");
Console.WriteLine("OnDisconnectedAsync");
await base.OnDisconnectedAsync(exception);
}
}