연결 수명 주기 관리
연결 열기, 닫기, 예기치 않은 연결 해제를 포함하여 WebSocket 연결의 수명 주기를 관리합니다.
연결 수명 주기 관리은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.
자주 묻는 질문
“연결 수명 주기 관리” 강의는 무료인가요?
네 — “연결 수명 주기 관리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
“연결 수명 주기 관리”에서 뭘 배우나요?
연결 열기, 닫기, 예기치 않은 연결 해제를 포함하여 WebSocket 연결의 수명 주기를 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Real-Time Systems with Spring을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Real-Time Systems with Spring은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“연결 수명 주기 관리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Real-Time Systems with Spring 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Real-Time Systems with Spring 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.