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

การตั้งค่าเอ็นด์พอยต์ WebSocket

ตั้งค่าเอ็นด์พอยต์ WebSocket ใน Spring โดยกำหนดเส้นทางและจัดการการเชื่อมต่อเริ่มต้น

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

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What are WebSocket Endpoints?

Imagine a special doorway for real-time communication. In Spring, this doorway is called a WebSocket endpoint.

It's a specific URL path, like /ws or /chat, that your clients (e.g., web browsers) connect to for WebSocket communication. Without it, your server wouldn't know where to listen for real-time requests!

Spring Boot App Entry Point

Before configuring WebSockets, let's recall our Spring Boot application's main entry point. This is where your application starts running.

The @SpringBootApplication annotation simplifies setup by bundling common Spring annotations.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}

Enabling WebSocket Support

To tell Spring Boot that you want to use WebSockets, you need to enable it. This is done with a simple annotation on a configuration class.

  • Add @Configuration to mark the class as a Spring configuration.
  • Use @EnableWebSocket to activate Spring's WebSocket module.

This sets the stage for defining your endpoints.

The WebSocketConfigurer Interface

To customize how WebSockets are handled, Spring provides the WebSocketConfigurer interface. You'll implement this interface in your configuration class.

It gives you a method to override where you can register your specific WebSocket handlers and their paths.

Registering Your First Endpoint

Inside your WebSocketConfigurer implementation, you'll override the registerWebSocketHandlers method. This method takes a WebSocketHandlerRegistry object.

The registry is used to add your WebSocketHandler instances and map them to specific URL paths.

Defining the Endpoint Path

The core of endpoint configuration is the addHandler() method. It takes two main arguments:

  • Your WebSocketHandler instance (what handles messages).
  • The URL path where clients will connect (e.g., /mywebsocket).

Example: registry.addHandler(myHandler(), "/mywebsocket");

CORS and SockJS Fallback

You might need to allow connections from different domains (CORS) or support older browsers. The addHandler() method offers fluent options:

  • .setAllowedOrigins("*"): Allows connections from any domain. For production, specify exact domains.
  • .withSockJS(): Enables SockJS fallback, providing an alternative transport for browsers that don't fully support WebSockets.

Example: WebSocketConfig Class

Here's how your full configuration class might look. Notice how we implement WebSocketConfigurer and register a handler for the /ws path.

The myHandler() method creates an instance of our custom handler (defined next).

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.context.annotation.Bean;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(myHandler(), "/ws")
            .setAllowedOrigins("*");
  }

  @Bean
  public MyWebSocketHandler myHandler() {
    return new MyWebSocketHandler();
  }
}

Example: Basic WebSocket Handler

This is a very simple MyWebSocketHandler. It extends TextWebSocketHandler and just logs when a connection is established or closed. We'll dive deeper into handling messages in the next lesson!

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class MyWebSocketHandler extends TextWebSocketHandler {

  @Override
  public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    System.out.println("Connection established: " + session.getId());
  }

  @Override
  public void afterConnectionClosed(WebSocketSession session, 
                                    org.springframework.web.socket.CloseStatus status) 
                                    throws Exception {
    System.out.println("Connection closed: " + session.getId() + " - " + status.getReason());
  }

  // Message handling will go here in a later lesson
  @Override
  protected void handleTextMessage(WebSocketSession session, TextMessage message) {
    // For now, we just acknowledge. Message processing is next lesson.
    System.out.println("Received message (not processed yet): " + message.getPayload());
  }
}

Endpoint Config Check

You want to set up a WebSocket endpoint at the path /chat that allows connections from any origin and uses SockJS fallback. Which configuration snippet is correct?

Recap: WebSocket Endpoints

Great job! You've learned how to configure WebSocket endpoints in Spring Boot:

  • You use @EnableWebSocket on a @Configuration class.
  • You implement WebSocketConfigurer and override registerWebSocketHandlers.
  • Inside, you use registry.addHandler() to map a WebSocketHandler to a URL path.
  • Options like setAllowedOrigins() and withSockJS() enhance compatibility.

Next, we'll dive into how to send and receive messages using these handlers!

คำถามที่พบบ่อย

บทเรียน “การตั้งค่าเอ็นด์พอยต์ WebSocket” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การตั้งค่าเอ็นด์พอยต์ WebSocket”

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

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

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

บทเรียน “การตั้งค่าเอ็นด์พอยต์ WebSocket” ใช้เวลานานแค่ไหน

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

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

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

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

  1. Spring Boot สำหรับ WebSockets
  2. การตั้งค่าเอ็นด์พอยต์ WebSocket
  3. การส่งข้อความระหว่างไคลเอ็นต์กับเซิร์ฟเวอร์เบื้องต้น
  4. การจัดการเหตุการณ์วงจรชีวิตของ WebSocket ใน Spring
← กลับไปที่ WebSockets & Real-Time Systems with Spring