0Pricing
WebSockets & Real-Time Systems with Spring · บทเรียน

การส่งข้อความส่วนตัวด้วย STOMP

เรียนรู้การนำการส่งข้อความส่วนตัวแบบตัวต่อตัวระหว่างผู้ใช้ด้วยปลายทางผู้ใช้ของ STOMP ไปใช้

การส่งข้อความส่วนตัวด้วย STOMP เป็นบทเรียน WebSockets & Real-Time Systems with Spring ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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.

  • /user prefix: 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:

  1. username: The identifier of the recipient user.
  2. destination: The specific queue within that user's private space (e.g., /queue/private-messages).
  3. 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-messages

Spring 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 /user destination 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” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Real-Time Systems with Spring ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การส่งข้อความส่วนตัวด้วย STOMP”

เรียนรู้การนำการส่งข้อความส่วนตัวแบบตัวต่อตัวระหว่างผู้ใช้ด้วยปลายทางผู้ใช้ของ STOMP ไปใช้ คุณปฏิบัติ WebSockets & Real-Time Systems with Spring ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Real-Time Systems with Spring หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Real-Time Systems with Spring บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การส่งข้อความส่วนตัวด้วย STOMP” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Real-Time Systems with Spring นี้ได้ไหม

ได้ บทเรียน WebSockets & Real-Time Systems with Spring ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การออกแบบแบบจำลองข้อความแชต
  2. การสร้างห้องแชตสาธารณะ
  3. การส่งข้อความส่วนตัวด้วย STOMP
  4. ตัวบ่งชี้การพิมพ์และสถานะออนไลน์
← กลับไปที่ WebSockets & Real-Time Systems with Spring