WebSockets & Real-Time Systems with Spring · 课时

在 Spring 中处理 WebSocket 生命周期事件

学习在 Spring 中通过使用 WebSocketHandler 处理连接、消息、错误和断开事件来管理 WebSocket 连接生命周期。

第 4 / 4 课13 个步骤

在 Spring 中处理 WebSocket 生命周期事件 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.

免费开始

用 AI 导师学习 WebSockets & Real-Time Systems with Spring — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「在 Spring 中处理 WebSocket 生命周期事件」课时是免费的吗?

是的 — 「在 Spring 中处理 WebSocket 生命周期事件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。

「在 Spring 中处理 WebSocket 生命周期事件」这节课中我会学到什么?

学习在 Spring 中通过使用 WebSocketHandler 处理连接、消息、错误和断开事件来管理 WebSocket 连接生命周期。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 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