0Pricing
WebSockets & Real-Time Systems with Spring · 课时

WebSocket 端点配置

在 Spring 中配置 WebSocket 端点,定义路径并处理初始连接。

WebSocket 端点配置 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。

「WebSocket 端点配置」这节课中我会学到什么?

在 Spring 中配置 WebSocket 端点,定义路径并处理初始连接。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Real-Time Systems with Spring 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Real-Time Systems with Spring 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「WebSocket 端点配置」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebSockets & Real-Time Systems with Spring 课中编写并运行代码吗?

能。每节 WebSockets & Real-Time Systems with Spring 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 用于 WebSockets 的 Spring Boot
  2. WebSocket 端点配置
  3. 客户端与服务器的基本消息传递
  4. 在 Spring 中处理 WebSocket 生命周期事件
← 返回 WebSockets & Real-Time Systems with Spring