0Pricing
WebSockets & Real-Time Systems with Spring · Ders

Bağlantı Yaşam Döngüsü Yönetimi

WebSocket bağlantılarının açılması, kapatılması ve beklenmedik kopmalar dâhil olmak üzere bağlantı yaşam döngülerini yönetin.

Bağlantı Yaşam Döngüsü Yönetimi, CoddyKit'te ücretsiz bir WebSockets & Real-Time Systems with Spring dersidir. Bu, 4 dersinin 2. 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.

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.

Sıkça Sorulan Sorular

“Bağlantı Yaşam Döngüsü Yönetimi” dersi ücretsiz mi?

Evet — “Bağlantı Yaşam Döngüsü Yönetimi” 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.

“Bağlantı Yaşam Döngüsü Yönetimi” dersinde ne öğreneceğim?

WebSocket bağlantılarının açılması, kapatılması ve beklenmedik kopmalar dâhil olmak üzere bağlantı yaşam döngülerini yönetin. 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 2. dersidir.

“Bağlantı Yaşam Döngüsü Yönetimi” 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

  1. WebSocket Hatalarını Uygun Şekilde Ele Alma
  2. Bağlantı Yaşam Döngüsü Yönetimi
  3. Yeniden Denemeler ve Geri Dönüşler
  4. Kalp Atışları ve Ping/Pong Canlı Tutma
← WebSockets & Real-Time Systems with Spring Sayfasına Dön