Spring'de WebSocket Yaşam Döngüsü Olaylarını Yönetme
WebSocket bağlantısının yaşam döngüsünü Spring'de WebSocketHandler ile bağlanma, ileti, hata ve bağlantı kesilmesi olaylarını işleyerek yönetmeyi öğrenin.
Spring'de WebSocket Yaşam Döngüsü Olaylarını Yönetme, CoddyKit'te ücretsiz bir WebSockets & Real-Time Systems with Spring dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, WebSockets & Real-Time Systems with Spring öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. WebSockets & Real-Time Systems with Spring kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
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.
Sıkça Sorulan Sorular
“Spring'de WebSocket Yaşam Döngüsü Olaylarını Yönetme” dersi ücretsiz mi?
Evet — “Spring'de WebSocket Yaşam Döngüsü Olaylarını Yönetme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve WebSockets & Real-Time Systems with Spring kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. WebSockets & Real-Time Systems with Spring kursu toplamda 4 dersten oluşur.
“Spring'de WebSocket Yaşam Döngüsü Olaylarını Yönetme” dersinde ne öğreneceğim?
WebSocket bağlantısının yaşam döngüsünü Spring'de WebSocketHandler ile bağlanma, ileti, hata ve bağlantı kesilmesi olaylarını işleyerek yönetmeyi öğrenin. WebSockets & Real-Time Systems with Spring ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
WebSockets & Real-Time Systems with Spring öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te WebSockets & Real-Time Systems with Spring, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.
“Spring'de WebSocket Yaşam Döngüsü Olaylarını Yönetme” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu WebSockets & Real-Time Systems with Spring dersinde kod yazıp çalıştırabilir miyim?
Evet. Her WebSockets & Real-Time Systems with Spring dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- WebSockets için Spring Boot
- WebSocket Uç Noktası Yapılandırması
- Temel İstemci-Sunucu Mesajlaşması
- Spring'de WebSocket Yaşam Döngüsü Olaylarını Yönetme