0Pricing
WebSockets & Real-Time Systems with Spring · レッスン

SpringでのWebSocketライフサイクルイベント処理

WebSocketHandlerで接続、メッセージ、エラー、切断のイベントを処理し、SpringでWebSocket接続のライフサイクルを管理する方法を学びます。

「SpringでのWebSocketライフサイクルイベント処理」はCoddyKit上の無料WebSockets & Real-Time Systems with Springレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWebSockets & Real-Time Systems with Spring学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 WebSockets & Real-Time Systems with Springコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

The Connection Lifecycle

A WebSocket connection moves through clear stages: it opens, exchanges messages, may hit errors, and finally closes. Spring lets you hook into each stage to manage state and resources cleanly.

This lesson covers handling those lifecycle events.

The WebSocketHandler Interface

Spring's low-level API centers on the WebSocketHandler interface. Extending TextWebSocketHandler gives you override points for each lifecycle event without implementing every method.

Connection Established

afterConnectionEstablished fires when a client successfully connects. Use it to register the session and initialize per-connection state.

@Override
public void afterConnectionEstablished(WebSocketSession session) {
    sessions.put(session.getId(), session);
    System.out.println('Connected: ' + session.getId());
}

Tracking Sessions

Keep active sessions in a thread-safe collection so you can broadcast and clean up. A ConcurrentHashMap keyed by session id is a common choice.

private final Map<String, WebSocketSession> sessions =
        new ConcurrentHashMap<>();

Handling Messages

handleTextMessage runs for each incoming message. Here you parse, validate, and act on the payload, then optionally reply or broadcast.

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    String payload = message.getPayload();
    session.sendMessage(new TextMessage('echo: ' + payload));
}

Handling Transport Errors

handleTransportError is called when a low-level error occurs on the connection. Log the problem and close the session gracefully if it cannot recover.

@Override
public void handleTransportError(WebSocketSession session, Throwable ex) throws Exception {
    System.out.println('Transport error: ' + ex.getMessage());
    if (session.isOpen()) {
        session.close(CloseStatus.SERVER_ERROR);
    }
}

Connection Closed

afterConnectionClosed fires when the connection ends, whether the client left or the server closed it. Always clean up here to avoid leaks.

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
    sessions.remove(session.getId());
    System.out.println('Closed: ' + status.getCode());
}

Close Status Codes

Close events carry a status code explaining why:

  • 1000 Normal closure
  • 1001 Going away (page unload)
  • 1006 Abnormal closure (no close frame)
  • 1011 Server error

Logging these helps diagnose connection problems.

Registering the Handler

Wire the handler to a path in a configuration class implementing WebSocketConfigurer.

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(new MyHandler(), '/ws')
            .setAllowedOrigins('https://app.example.com');
}

Cleaning Up Resources

Per-connection resources (timers, subscriptions, buffers) must be released on close and on error. Failing to do so causes memory leaks that grow with every dropped connection.

Heartbeats and Idle Timeouts

Dead connections may never fire a clean close. Use ping/pong heartbeats or idle timeouts to detect and reap stale sessions so your session map stays accurate.

Quick Check

Test your understanding of the WebSocket lifecycle.

Recap

You learned to handle the WebSocket lifecycle in Spring with TextWebSocketHandler: track sessions on connect, process messages, handle transport errors, and clean up on close. Close status codes, heartbeats, and idle timeouts keep your connection state healthy and leak-free.

よくある質問

「SpringでのWebSocketライフサイクルイベント処理」レッスンは無料ですか?

はい。「SpringでのWebSocketライフサイクルイベント処理」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、WebSockets & Real-Time Systems with Springコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 WebSockets & Real-Time Systems with Springコースには全4レッスンが含まれています。

「SpringでのWebSocketライフサイクルイベント処理」で何を学びますか?

WebSocketHandlerで接続、メッセージ、エラー、切断のイベントを処理し、SpringでWebSocket接続のライフサイクルを管理する方法を学びます。 ブラウザで直接実行するハンズオンコードでWebSockets & Real-Time Systems with Springを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

WebSockets & Real-Time Systems with Springを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのWebSockets & Real-Time Systems with Springは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「Springでの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に戻る