그룹, 사용자와 연결 관리
그룹을 관리하고 특정 사용자 또는 연결을 대상으로 지정하며 연결 및 연결 해제 수명 주기 이벤트를 처리합니다.
그룹, 사용자와 연결 관리은(는) CoddyKit의 무료 C# Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C# Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C# Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
그룹과 사용자가 필요한 이유
실제 애플리케이션에서는 ALL 클라이언트에 브로드캐스트하려는 경우가 거의 없습니다. SignalR의 그룹을 사용하면 connection의 일부(예: 채팅방)를 대상으로 지정할 수 있고, 사용자를 사용하면 특정 인증 사용자의 모든 연결에 주소를 지정할 수 있습니다.
그룹에 연결 추가하기
connection ID와 그룹 이름을 사용하여 Groups.AddToGroupAsync()를 호출하십시오. 하나의 connection은 동시에 여러 그룹에 속할 수 있습니다.
public class ChatHub : Hub
{
public async Task JoinRoom(string roomName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, roomName);
await Clients.Group(roomName)
.SendAsync("UserJoined", Context.User!.Identity!.Name);
}
public async Task LeaveRoom(string roomName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, roomName);
await Clients.Group(roomName)
.SendAsync("UserLeft", Context.User!.Identity!.Name);
}
}그룹에 보내기
Clients.Group(name)을 사용하여 그룹의 모든 연결에 보내십시오. 그 밖의 대상 지정 옵션으로는 GroupExcept와 Groups(한 번에 여러 그룹)가 있습니다.
public async Task SendToRoom(string roomName, string message)
{
var sender = Context.User!.Identity!.Name;
// Everyone in the room
await Clients.Group(roomName)
.SendAsync("ReceiveMessage", sender, message);
// Everyone in the room except the sender
await Clients.GroupExcept(roomName, Context.ConnectionId)
.SendAsync("ReceiveMessage", sender, message);
}사용자 기반 대상 지정
사용자가 여러 브라우저 탭이나 장치를 열어 두면 여러 connection을 갖게 됩니다. Clients.User(userId)는 해당 사용자의 모든 connection에 동시에 보냅니다.
// Send to all connections of user with ID "user-123"
await Clients.User("user-123")
.SendAsync("Notification", "Your order has shipped!");
// SignalR uses the NameIdentifier claim by default.
// Context.UserIdentifier returns the current user's ID.
var myId = Context.UserIdentifier;
await Clients.User(myId!).SendAsync("Ack", "Server received your message");사용자 ID 공급자 사용자 지정하기
기본적으로 SignalR은 NameIdentifier 클레임을 사용자 ID로 사용합니다. 다른 클레임이나 사용자 지정 로직을 사용하려면 IUserIdProvider를 구현하십시오.
public class EmailUserIdProvider : IUserIdProvider
{
public string? GetUserId(HubConnectionContext connection)
{
return connection.User?.FindFirst(ClaimTypes.Email)?.Value;
}
}
// Register:
builder.Services.AddSingleton<IUserIdProvider, EmailUserIdProvider>();Connection 상태 추적하기
SignalR은 연결이 끊긴 동안 connection 상태를 유지하지 않습니다. 사용자 ID와 connection ID의 매핑을 스레드 안전한 딕셔너리에 직접 추적하십시오(단일 서버에서는 딕셔너리, 다중 서버에서는 Redis).
public class ConnectionTracker
{
private readonly ConcurrentDictionary<string, HashSet<string>> _userConnections
= new();
public void AddConnection(string userId, string connectionId)
=> _userConnections.GetOrAdd(userId, _ => new()).Add(connectionId);
public void RemoveConnection(string userId, string connectionId)
{
if (_userConnections.TryGetValue(userId, out var conns))
{
conns.Remove(connectionId);
if (conns.Count == 0) _userConnections.TryRemove(userId, out _);
}
}
public IEnumerable<string> GetConnections(string userId)
=> _userConnections.TryGetValue(userId, out var c) ? c : Enumerable.Empty<string>();
}OnConnected/OnDisconnected에서 그룹 자동 관리하기
일반적인 패턴은 인증된 사용자를 OnConnectedAsync에서 개인 그룹에 자동으로 추가하는 것입니다. 그러면 사용자 지정 추적 없이 그룹 이름으로 해당 사용자를 대상으로 지정할 수 있습니다.
public override async Task OnConnectedAsync()
{
// Add to a personal group named by user ID
var userId = Context.UserIdentifier;
if (userId is not null)
await Groups.AddToGroupAsync(Context.ConnectionId, userId);
await base.OnConnectedAsync();
}
// Now send to a user by their personal group:
await _hub.Clients.Group(userId)
.SendAsync("Update", payload);그룹을 사용하여 백그라운드 서비스에서 보내기
IHubContext를 사용하면 백그라운드 서비스에서 그룹과 사용자를 대상으로 지정할 수 있습니다. 시스템의 이벤트로 트리거되는 async 알림에 적합합니다.
public class OrderShippedHandler : INotificationHandler<OrderShipped>
{
private readonly IHubContext<OrderHub> _hub;
public OrderShippedHandler(IHubContext<OrderHub> hub) => _hub = hub;
public async Task Handle(OrderShipped notification, CancellationToken ct)
{
// Push to the customer's personal group
await _hub.Clients.Group(notification.CustomerId.ToString())
.SendAsync("OrderShipped",
new { notification.OrderId, notification.TrackingNumber },
ct);
}
}그룹 멤버십 유지
그룹 멤버십은 저장되지 않습니다. 서버가 다시 시작되거나 Redis 백플레인이 상태를 잃으면 그룹은 비어 있습니다. 클라이언트의 onreconnected 이벤트를 사용해 다시 연결할 때 그룹에 다시 가입하십시오.
// JavaScript client: re-join groups after reconnect
connection.onreconnected(async connectionId => {
console.log(`Reconnected as ${connectionId}`);
// Re-join previously joined rooms
for (const room of joinedRooms) {
await connection.invoke("JoinRoom", room);
}
});접속 상태: 온라인/오프라인 감지
OnConnected/OnDisconnected에서 사용자별 연결 수를 세고 관련 그룹에 접속 상태 이벤트를 브로드캐스트하여 온라인 상태를 추적합니다.
public override async Task OnConnectedAsync()
{
var userId = Context.UserIdentifier!;
var count = _tracker.AddConnection(userId, Context.ConnectionId);
if (count == 1) // first connection for this user
await Clients.Others.SendAsync("UserOnline", userId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? ex)
{
var userId = Context.UserIdentifier!;
var count = _tracker.RemoveConnection(userId, Context.ConnectionId);
if (count == 0) // no more connections
await Clients.Others.SendAsync("UserOffline", userId);
await base.OnDisconnectedAsync(ex);
}빠른 확인
사용자에게 브라우저 탭이 세 개 열려 있을 때 Clients.User(userId)는 무엇을 수행합니까?
요약: 그룹, 사용자 및 연결 관리
핵심 내용:
Groups.AddToGroupAsync/RemoveFromGroupAsync: 그룹 멤버십을 관리합니다Clients.Group(name): 연결의 일부에 메시지를 보냅니다Clients.User(userId): 한 사용자의 모든 연결에 메시지를 보냅니다- 사용자 지정 사용자 ID 클레임을 사용하려면
IUserIdProvider를 구현합니다 - 그룹은 저장되지 않으므로 다시 연결할 때 다시 가입해야 합니다
- 접속 상태를 감지하려면 ConcurrentDictionary에서 연결 수를 추적합니다
자주 묻는 질문
“그룹, 사용자와 연결 관리” 강의는 무료인가요?
네 — “그룹, 사용자와 연결 관리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C# Academy 강의 전체를 잠금 해제할 수 있습니다. C# Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“그룹, 사용자와 연결 관리”에서 뭘 배우나요?
그룹을 관리하고 특정 사용자 또는 연결을 대상으로 지정하며 연결 및 연결 해제 수명 주기 이벤트를 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 C# Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
C# Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 C# Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“그룹, 사용자와 연결 관리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 C# Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 C# Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- SignalR 허브와 연결
- 그룹, 사용자와 연결 관리
- 강력한 형식의 허브
- Redis 백플레인으로 확장하기