检测在线状态与连接状态
使用 Realtime Database 在线状态功能、onDisconnect 处理程序和特殊的 .info/connected 节点,构建可靠反映连接状态的实时在线/离线指示器。
检测在线状态与连接状态 是 CoddyKit 上的免费 Firebase Auth & Realtime Database Apps 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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/connectedis true - Register the
onDisconnectaction 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/connectedfor live connection state - Use
onDisconnectso the server marks users offline - Register onDisconnect before going online
- Use server timestamps and per-connection tracking
- Cancel handlers on clean logout
用 AI 导师学习 Firebase Auth & Realtime Database Apps — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 11
- 课程
- 44
常见问题解答
「检测在线状态与连接状态」课时是免费的吗?
是的 — 「检测在线状态与连接状态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Firebase Auth & Realtime Database Apps 课程的其余内容,请升级到 CoddyKit PRO。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。
「检测在线状态与连接状态」这节课中我会学到什么?
使用 Realtime Database 在线状态功能、onDisconnect 处理程序和特殊的 .info/connected 节点,构建可靠反映连接状态的实时在线/离线指示器。 你通过在浏览器中直接运行的动手代码来练习 Firebase Auth & Realtime Database Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Firebase Auth & Realtime Database Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Firebase Auth & Realtime Database Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「检测在线状态与连接状态」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Firebase Auth & Realtime Database Apps 课中编写并运行代码吗?
能。每节 Firebase Auth & Realtime Database Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。