STOMP를 사용한 비공개 메시징
STOMP의 사용자별 대상을 사용하여 사용자 간 일대일 비공개 메시징을 구현하는 방법을 학습합니다.
STOMP를 사용한 비공개 메시징은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Real-Time Systems with Spring 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Private Chat Essentials
Welcome! In this lesson, we'll learn how to build private messaging functionality into our chat application using WebSockets and STOMP.
Unlike public chat rooms where everyone receives messages, private messages (like direct messages or DMs) are sent specifically from one user to another. This requires a way to route messages directly to an individual's unique session.
STOMP User Destinations
STOMP provides a special destination prefix: /user. When a client subscribes to a destination like /user/queue/private-messages, the STOMP broker (and Spring) automatically translate this into a unique, session-specific queue for that particular authenticated user.
/userprefix: Indicates a user-specific destination.- Unique per user: Each user gets their own 'inbox' for private messages.
- Abstracted routing: You don't need to know the actual session ID.
Spring & User Routes
Spring's WebSocket and STOMP integration works hand-in-hand with the /user prefix. When you configure your message broker, you tell Spring to enable user destinations:
config.setUserDestinationPrefix("/user");This setting ensures that messages addressed to /user/{username}/queue/{destination} are correctly routed by Spring to the WebSocket session(s) associated with {username}.
Server-Side: Sending Private Messages
On the server, Spring provides the SimpMessagingTemplate. This powerful tool allows you to send messages to various STOMP destinations, including user-specific ones.
The key method for private messaging is convertAndSendToUser(). It takes three main arguments:
username: The identifier of the recipient user.destination: The specific queue within that user's private space (e.g.,/queue/private-messages).payload: The actual message content.
Server Private Send Demo
Try running this simplified Spring Boot application. It shows a controller method that sends a private message using SimpMessagingTemplate. Remember, in a real app, the recipient's username would come from the client's message payload or other context.
package com.coddykit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import java.security.Principal;
@SpringBootApplication
@EnableWebSocketMessageBroker
public class PrivateChatApp {
public static void main(String[] args) {
SpringApplication.run(PrivateChatApp.class, args);
}
@Configuration
static class WsConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry cfg) {
cfg.enableSimpleBroker("/topic", "/queue");
cfg.setApplicationDestinationPrefixes("/app");
cfg.setUserDestinationPrefix("/user"); // Crucial for private messages
}
@Override
public void registerStompEndpoints(StompEndpointRegistry reg) {
reg.addEndpoint("/ws").withSockJS();
}
}
@Controller
static class PrivateMsgController {
private final SimpMessagingTemplate template;
public PrivateMsgController(SimpMessagingTemplate t) {
this.template = t;
}
@MessageMapping("/sendPrivate") // Client sends to /app/sendPrivate
public void sendPrivateMsg(String msg, Principal p) {
String sender = p != null ? p.getName() : "anon";
String recipient = "targetUser"; // In real app, from msg payload
// Send to a specific user's private queue
template.convertAndSendToUser(
recipient,
"/queue/private-messages", // Client subscribes here
"From " + sender + ": " + msg
);
System.out.println("Sent private msg to " + recipient + " from " + sender);
}
}
}Client's Private Inbox
On the client side, a user needs to subscribe to their own private destination to receive messages. If a user's principal name is 'alice', they would subscribe to:
/user/queue/private-messagesSpring automatically maps this to /queue/private-messages-user{sessionId} internally, ensuring only 'alice' receives messages sent to her.
Client-Side Subscription
Using a STOMP client library (like Stomp.js), the subscription process is straightforward:
stompClient.subscribe('/user/queue/private-messages', function(message) {
// Handle the private message
console.log("Received private message: " + message.body);
});This ensures that any message sent to the currently authenticated user's /queue/private-messages destination will be received by this client.
Private Message Model
For robust private chat, your message payload should contain structured data. A typical private message model might include:
senderId: The ID of the user who sent the message.recipientId: The ID of the user intended to receive the message.content: The actual text or data of the message.timestamp: When the message was sent.
This allows clients to display messages correctly, identifying who sent what to whom.
User Identity & STOMP
How does Spring know which user is 'alice' for the /user destination? It relies on the Principal object, which is usually populated by Spring Security or another authentication mechanism.
When a WebSocket connection is established, Spring associates a Principal with that session. The convertAndSendToUser() method uses the getName() of this Principal to identify the target user.
Private Message Quiz
You've learned how Spring and STOMP handle private messages. Let's test your understanding of sending them.
Private Chat Summary
Great job! You've learned the fundamentals of implementing private messaging with STOMP and Spring.
- The
/userdestination prefix routes messages to individual users. - Spring's
SimpMessagingTemplate.convertAndSendToUser()sends messages to specific user destinations. - Clients subscribe to
/user/queue/{your-private-destination}to receive their DMs. - User identity (
Principal) is crucial for correct routing.
This knowledge allows you to build sophisticated, personalized real-time interactions in your applications!
자주 묻는 질문
“STOMP를 사용한 비공개 메시징” 강의는 무료인가요?
네 — “STOMP를 사용한 비공개 메시징” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
“STOMP를 사용한 비공개 메시징”에서 뭘 배우나요?
STOMP의 사용자별 대상을 사용하여 사용자 간 일대일 비공개 메시징을 구현하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Real-Time Systems with Spring을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Real-Time Systems with Spring은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“STOMP를 사용한 비공개 메시징” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Real-Time Systems with Spring 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Real-Time Systems with Spring 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 채팅 메시지 모델 설계
- 공개 채팅방 구현
- STOMP를 사용한 비공개 메시징
- 입력 중 표시 및 온라인 상태