WebSocketエンドポイントの設定
SpringでWebSocketエンドポイントを設定し、パスを定義して初期接続を処理します。
「WebSocketエンドポイントの設定」はCoddyKit上の無料WebSockets & Real-Time Systems with Springレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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
@Configurationto mark the class as a Spring configuration. - Use
@EnableWebSocketto 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
WebSocketHandlerinstance (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
@EnableWebSocketon a@Configurationclass. - You implement
WebSocketConfigurerand overrideregisterWebSocketHandlers. - Inside, you use
registry.addHandler()to map aWebSocketHandlerto a URL path. - Options like
setAllowedOrigins()andwithSockJS()enhance compatibility.
Next, we'll dive into how to send and receive messages using these handlers!
よくある質問
「WebSocketエンドポイントの設定」レッスンは無料ですか?
はい。「WebSocketエンドポイントの設定」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応の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を演習し、24時間対応の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フィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- WebSockets向けSpring Boot
- WebSocketエンドポイントの設定
- クライアントとサーバー間の基本メッセージング
- SpringでのWebSocketライフサイクルイベント処理