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

连接生命周期管理

管理 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 节课。

本课时的部分内容尚未翻译,以英文显示。

WebSocket Connection Lifecycle

Every WebSocket connection goes through a lifecycle: it opens, stays active for messaging, and eventually closes. Managing these stages is crucial for building robust real-time applications.

Proper lifecycle management helps ensure resources are used efficiently and that your application responds gracefully to various connection events.

The Initial Handshake

Before a WebSocket connection is established, an initial HTTP handshake occurs. The client sends an HTTP request with an Upgrade header, asking to switch protocols.

If the server agrees, it responds with a 101 Switching Protocols status, and the connection transitions from HTTP to WebSocket.

Client-Side Connection

On the client side, typically in a web browser, you initiate a WebSocket connection using JavaScript. The WebSocket constructor creates a new connection to the specified URL.

This example shows how to connect and log messages when the connection opens or encounters an error.

const socket = new WebSocket("ws://localhost:8080/lifecycle");

socket.onopen = () => {
  console.log("WebSocket Connected!");
};

socket.onerror = (error) => {
  console.error("WebSocket Error:", error);
};

Server-Side: Handling New Connections

In Spring, you can use the @OnOpen annotation to define a method that executes when a new WebSocket connection is established. This is your entry point for handling new clients.

The Session object provides details about the client connection.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@SpringBootApplication
public class WebSocketLifecycleApp {
    public static void main(String[] args) {
        SpringApplication.run(WebSocketLifecycleApp.class, args);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

@ServerEndpoint("/lifecycle")
@Component
class LifecycleHandler {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Client connected: " + session.getId());
    }
}

Gracefully Closing Connections

A connection can be closed intentionally by either the client or the server. This is called a 'graceful' closure. It's important to close connections properly to release server resources and inform clients.

A close message usually includes a status code and a reason for closure, helping both ends understand why the connection ended.

Client-Side Disconnect

Clients can close a WebSocket connection using the close() method. You can optionally provide a status code and a reason message.

The onclose event listener is triggered when the connection is closed, allowing you to perform cleanup or UI updates.

socket.onclose = (event) => {
  if (event.wasClean) {
    console.log(`Closed cleanly, code=${event.code}, reason=${event.reason}`);
  } else {
    console.log('Connection died unexpectedly');
  }
};

// To close the connection explicitly:
socket.close(1000, "Client leaving");

Server-Side: Handling Disconnections

The @OnClose annotation in Spring allows you to define a method that executes when a WebSocket connection is closed. This is where you can clean up resources associated with that session.

The CloseReason parameter provides details about why the connection was terminated.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.websocket.OnOpen;
import javax.websocket.OnClose;
import javax.websocket.Session;
import javax.websocket.CloseReason;
import javax.websocket.server.ServerEndpoint;

@SpringBootApplication
public class WebSocketLifecycleApp {
    public static void main(String[] args) {
        SpringApplication.run(WebSocketLifecycleApp.class, args);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

@ServerEndpoint("/lifecycle")
@Component
class LifecycleHandler {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Client connected: " + session.getId());
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        System.out.println("Client disconnected: " + session.getId() + " - Reason: " + reason.getReasonPhrase());
    }
}

Handling Unexpected Disconnections & Errors

Sometimes connections don't close gracefully. Network issues, client crashes, or server errors can lead to abrupt disconnections. These are 'unclean' closures.

It's vital to have mechanisms to detect and respond to these unexpected events to maintain application stability and user experience.

Server-Side: Error Handling

The @OnError annotation handles exceptions that occur during a WebSocket session. This could be due to issues like message processing errors or underlying network problems.

Implementing an @OnError handler ensures your server can log errors and potentially close the affected session gracefully, preventing resource leaks.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.websocket.OnOpen;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.Session;
import javax.websocket.CloseReason;
import javax.websocket.server.ServerEndpoint;

@SpringBootApplication
public class WebSocketLifecycleApp {
    public static void main(String[] args) {
        SpringApplication.run(WebSocketLifecycleApp.class, args);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

@ServerEndpoint("/lifecycle")
@Component
class LifecycleHandler {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Client connected: " + session.getId());
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        System.out.println("Client disconnected: " + session.getId() + " - Reason: " + reason.getReasonPhrase());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("Error on session " + session.getId() + ": " + throwable.getMessage());
    }
}

Detecting Liveness with Heartbeats

When a connection drops unexpectedly (e.g., network cable pulled), neither side might immediately know. Heartbeat mechanisms, often using WebSocket ping/pong frames, help detect unresponsive peers.

By sending periodic pings and expecting pongs, you can determine if a connection is still alive and close it if no response is received.

Lifecycle Management Check

Managing the various stages of a WebSocket connection is key to building reliable real-time applications. Let's test your understanding of Spring's lifecycle annotations.

Recap: Connection Management

In this lesson, you've learned about the crucial aspects of WebSocket connection lifecycle management. We covered:

  • The initial HTTP handshake.
  • How clients and servers open connections (@OnOpen).
  • Graceful client and server disconnections (@OnClose).
  • Handling unexpected errors during a session (@OnError).
  • The role of heartbeats in detecting unresponsive connections.

Mastering these concepts is fundamental for developing robust and resilient real-time applications with WebSockets and Spring.

常见问题解答

「连接生命周期管理」课时是免费的吗?

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

「连接生命周期管理」这节课中我会学到什么?

管理 WebSocket 连接的生命周期,包括建立连接、关闭连接和意外断开连接。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

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

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

「连接生命周期管理」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. 优雅处理 WebSocket 错误
  2. 连接生命周期管理
  3. 重试与回退
  4. 心跳与 Ping/Pong 保活
← 返回 WebSockets & Real-Time Systems with Spring