Private Nachrichten mit STOMP
Lernen Sie, mit den Benutzerzielen von STOMP direkte private Nachrichten zwischen einzelnen Benutzern zu implementieren.
Private Nachrichten mit STOMP ist eine kostenlose WebSockets & Real-Time Systems with Spring-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des WebSockets & Real-Time Systems with Spring-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der WebSockets & Real-Time Systems with Spring-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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!
Häufig gestellte Fragen
Ist die Lektion „Private Nachrichten mit STOMP“ kostenlos?
Ja — der vollständige Text von „Private Nachrichten mit STOMP“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des WebSockets & Real-Time Systems with Spring-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der WebSockets & Real-Time Systems with Spring-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Private Nachrichten mit STOMP“?
Lernen Sie, mit den Benutzerzielen von STOMP direkte private Nachrichten zwischen einzelnen Benutzern zu implementieren. Du übst WebSockets & Real-Time Systems with Spring mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um WebSockets & Real-Time Systems with Spring zu starten?
Keine Vorkenntnisse erforderlich. WebSockets & Real-Time Systems with Spring auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.
Wie lange dauert die Lektion „Private Nachrichten mit STOMP“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser WebSockets & Real-Time Systems with Spring-Lektion Code schreiben und ausführen?
Ja. Jede WebSockets & Real-Time Systems with Spring-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Ein Nachrichtenmodell für Chats entwerfen
- Öffentliche Chaträume implementieren
- Private Nachrichten mit STOMP
- Tippindikatoren und Online-Status