Handling WebSocket Lifecycle Events in Spring
Learn to manage the WebSocket connection lifecycle in Spring by handling connect, message, error, and disconnect events with WebSocketHandler.
Handling WebSocket Lifecycle Events in Spring is a free WebSockets & Real-Time Systems with Spring lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the WebSockets & Real-Time Systems with Spring learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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.
Frequently asked questions
Is the “Handling WebSocket Lifecycle Events in Spring” lesson free?
Yes — the full text of “Handling WebSocket Lifecycle Events in Spring” is free to read here on the web, and the WebSockets & Real-Time Systems with Spring course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the WebSockets & Real-Time Systems with Spring course, upgrade to CoddyKit PRO.
What will I learn in “Handling WebSocket Lifecycle Events in Spring”?
Learn to manage the WebSocket connection lifecycle in Spring by handling connect, message, error, and disconnect events with WebSocketHandler. You practise WebSockets & Real-Time Systems with Spring with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start WebSockets & Real-Time Systems with Spring?
No prior experience is required. WebSockets & Real-Time Systems with Spring on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Handling WebSocket Lifecycle Events in Spring” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this WebSockets & Real-Time Systems with Spring lesson?
Yes. Every WebSockets & Real-Time Systems with Spring lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Spring Boot for WebSockets
- WebSocket Endpoint Configuration
- Basic Client-Server Messaging
- Handling WebSocket Lifecycle Events in Spring