Firebase Auth & Realtime Database Apps · درس

اكتشاف الحضور والحالة متصل/غير متصل

أنشئ مؤشرات مباشرة للحالة متصل/غير متصل باستخدام حضور Realtime Database، ومعالجات onDisconnect، والعقدة الخاصة .info/connected لعرض حالة الاتصال بشكل موثوق.

الدرس 4 من 413 خطوة

اكتشاف الحضور والحالة متصل/غير متصل درس مجاني في Firebase Auth & Realtime Database Apps على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Firebase Auth & Realtime Database Apps، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Firebase Auth & Realtime Database Apps 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

What Is Presence

Presence means knowing which users are currently online. Chat apps, collaborative tools, and games all rely on it to show 'active now' indicators.

Realtime Database has special features that make presence robust even when a client disconnects unexpectedly.

The Connection Challenge

The hard part is the ungraceful disconnect: a user closes their laptop or loses signal. The app never gets to set status to 'offline'. We need the server to do it for us.

The .info/connected Node

Firebase exposes a special read-only boolean at .info/connected that is true when the client has a live connection and false when it does not.

import { getDatabase, ref, onValue } from 'firebase/database';

const db = getDatabase();
onValue(ref(db, '.info/connected'), (snap) => {
  console.log('Connected?', snap.val() === true);
});

onDisconnect Basics

onDisconnect registers an action that the server performs when the client disconnects. It is the key to reliable presence.

import { onDisconnect, set } from 'firebase/database';

const statusRef = ref(db, 'status/' + uid);
onDisconnect(statusRef).set({ state: 'offline' });

Order of Operations

The correct sequence is critical:

  • Wait until .info/connected is true
  • Register the onDisconnect action first
  • Only then set status to online

This guarantees the offline handler is armed before you go online.

A Complete Presence Setup

Combining the pieces gives a reliable presence system.

onValue(ref(db, '.info/connected'), (snap) => {
  if (snap.val() !== true) return;
  onDisconnect(statusRef).set({ state: 'offline', at: Date.now() })
    .then(() => set(statusRef, { state: 'online', at: Date.now() }));
});

Server Timestamps

Use serverTimestamp() instead of the client clock so 'last seen' times are consistent across devices with skewed clocks.

import { serverTimestamp } from 'firebase/database';

set(statusRef, { state: 'online', lastChanged: serverTimestamp() });

Multiple Devices

A user may be online on phone and laptop at once. Track presence per connection (a unique key per session) and treat the user as offline only when all connections drop.

import { push } from 'firebase/database';

const conRef = push(ref(db, 'status/' + uid + '/connections'));
onDisconnect(conRef).remove();

Cancelling onDisconnect

If the user logs out cleanly, cancel the pending onDisconnect action and set offline yourself, so stale handlers do not fire later.

import { onDisconnect } from 'firebase/database';

await onDisconnect(statusRef).cancel();
await set(statusRef, { state: 'offline' });

Displaying Presence

Other clients simply listen to the status node. A green dot appears when state is online and disappears when the server flips it to offline on disconnect.

onValue(ref(db, 'status/' + otherUid), (snap) => {
  const online = snap.val()?.state === 'online';
  toggleDot(online);
});

Best Practices

Keep presence reliable and cheap:

  • Store presence in a shallow, dedicated node
  • Use server timestamps for last-seen
  • Account for multiple connections
  • Always register onDisconnect before going online

Quick Check

Test your understanding of presence.

Recap

You can now build reliable online indicators.

  • Watch .info/connected for live connection state
  • Use onDisconnect so the server marks users offline
  • Register onDisconnect before going online
  • Use server timestamps and per-connection tracking
  • Cancel handlers on clean logout
البدء مجانًا

تعلم Firebase Auth & Realtime Database Apps مع معلم ذكاء اصطناعي — مجانًا

اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.

الدورات
11
الدروس
44

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

هل درس «اكتشاف الحضور والحالة متصل/غير متصل» مجاني؟

نعم — نص درس «اكتشاف الحضور والحالة متصل/غير متصل» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Firebase Auth & Realtime Database Apps، انتقل إلى CoddyKit PRO. تتضمن دورة Firebase Auth & Realtime Database Apps 4 دروس في المجموع.

ماذا ستتعلم في «اكتشاف الحضور والحالة متصل/غير متصل»؟

أنشئ مؤشرات مباشرة للحالة متصل/غير متصل باستخدام حضور Realtime Database، ومعالجات onDisconnect، والعقدة الخاصة .info/connected لعرض حالة الاتصال بشكل موثوق. تتمرن على Firebase Auth & Realtime Database Apps مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Firebase Auth & Realtime Database Apps؟

لا تُشترط خبرة سابقة. Firebase Auth & Realtime Database Apps على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «اكتشاف الحضور والحالة متصل/غير متصل»؟

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

هل يمكنني كتابة وتشغيل أكواد في درس Firebase Auth & Realtime Database Apps هذا؟

نعم. كل درس في Firebase Auth & Realtime Database Apps يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

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

  1. تفعيل الاستمرارية دون اتصال
  2. معالجة انقطاعات الشبكة
  3. استراتيجيات مزامنة البيانات
  4. اكتشاف الحضور والحالة متصل/غير متصل
← العودة إلى Firebase Auth & Realtime Database Apps