0Pricing
WebSockets & Real-Time Systems with Spring · درس

التعامل مع أحداث دورة حياة WebSocket في Spring

تعلّم إدارة دورة حياة اتصال WebSocket في Spring عبر التعامل مع أحداث الاتصال والرسائل والأخطاء وقطع الاتصال باستخدام WebSocketHandler.

التعامل مع أحداث دورة حياة WebSocket في Spring درس مجاني في WebSockets & Real-Time Systems with Spring على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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.

الأسئلة الشائعة

هل درس «التعامل مع أحداث دورة حياة WebSocket في Spring» مجاني؟

نعم — نص درس «التعامل مع أحداث دورة حياة WebSocket في Spring» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة WebSockets & Real-Time Systems with Spring، انتقل إلى CoddyKit PRO. تتضمن دورة WebSockets & Real-Time Systems with Spring 4 دروس في المجموع.

ماذا ستتعلم في «التعامل مع أحداث دورة حياة WebSocket في Spring»؟

تعلّم إدارة دورة حياة اتصال WebSocket في Spring عبر التعامل مع أحداث الاتصال والرسائل والأخطاء وقطع الاتصال باستخدام WebSocketHandler. تتمرن على WebSockets & Real-Time Systems with Spring مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ WebSockets & Real-Time Systems with Spring؟

لا تُشترط خبرة سابقة. WebSockets & Real-Time Systems with Spring على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «التعامل مع أحداث دورة حياة WebSocket في Spring»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس WebSockets & Real-Time Systems with Spring هذا؟

نعم. كل درس في WebSockets & Real-Time Systems with Spring يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. Spring Boot لـ WebSockets
  2. إعداد نقاط نهاية WebSocket
  3. المراسلة الأساسية بين العميل والخادم
  4. التعامل مع أحداث دورة حياة WebSocket في Spring
← العودة إلى WebSockets & Real-Time Systems with Spring