0Pricing
WebSockets & Real-Time Systems with Spring · Lección

Configuración de endpoints WebSocket

Configure endpoints WebSocket en Spring, definiendo rutas y gestionando las conexiones iniciales.

Configuración de endpoints WebSocket es una lección gratuita de WebSockets & Real-Time Systems with Spring en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de WebSockets & Real-Time Systems with Spring, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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!

Preguntas frecuentes

¿La lección «Configuración de endpoints WebSocket» es gratis?

Sí — el texto completo de «Configuración de endpoints WebSocket» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de WebSockets & Real-Time Systems with Spring, actualiza a CoddyKit PRO. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.

¿Qué aprenderé en «Configuración de endpoints WebSocket»?

Configure endpoints WebSocket en Spring, definiendo rutas y gestionando las conexiones iniciales. Practicas WebSockets & Real-Time Systems with Spring con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar WebSockets & Real-Time Systems with Spring?

No se requiere experiencia previa. WebSockets & Real-Time Systems with Spring en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Configuración de endpoints WebSocket»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de WebSockets & Real-Time Systems with Spring?

Sí. Cada lección de WebSockets & Real-Time Systems with Spring incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Spring Boot para WebSockets
  2. Configuración de endpoints WebSocket
  3. Mensajería básica entre cliente y servidor
  4. Gestión de eventos del ciclo de vida de WebSocket en Spring
← Volver a WebSockets & Real-Time Systems with Spring