Spring에서 WebSocket 수명 주기 이벤트 처리
WebSocketHandler로 연결, 메시지, 오류, 연결 해제 이벤트를 처리해 Spring에서 WebSocket 연결 수명 주기를 관리하는 방법을 익혀 보세요.
Spring에서 WebSocket 수명 주기 이벤트 처리은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
“Spring에서 WebSocket 수명 주기 이벤트 처리”에서 뭘 배우나요?
WebSocketHandler로 연결, 메시지, 오류, 연결 해제 이벤트를 처리해 Spring에서 WebSocket 연결 수명 주기를 관리하는 방법을 익혀 보세요. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 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 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- WebSockets를 위한 Spring Boot
- WebSocket 엔드포인트 구성
- 기본 클라이언트-서버 메시징
- Spring에서 WebSocket 수명 주기 이벤트 처리