alf*_*eon 5 firebase firebase-realtime-database flutter google-cloud-firestore
我正在创建一个 Flutter 应用程序,必须几乎立即检测到用户从实时/firestore 数据库中脱机并通知其他用户相同的情况。
我已经尝试了在实时数据库中订阅 .info/connected 的推荐方法,并更新了 Firestore 数据库。
FirebaseDatabase.instance
.reference()
.child('.info')
.child('connected')
.onValue
.listen((data) {
if (data.snapshot.value == false) {
// Internet has been disconnected
setState(() {
state.connected = false;
});
userFirestoreRef.updateData({
'status': 'offline',
'lastChanged': FieldValue.serverTimestamp(),
});
}
userDbRef.onDisconnect().update({
'status': 'offline',
'lastChanged': ServerValue.timestamp
}).then((_) async {
// This resolves as soon as the server gets the request, not when the user disconnects
setState(() {
state.connected = true;
});
await userDbRef.update({
'status': 'online',
'lastChanged': ServerValue.timestamp,
}).catchError((e) => debugPrint('Error in realtime db auth, $e'));
await userFirestoreRef.updateData({
'status': 'online',
'lastChanged': FieldValue.serverTimestamp(),
}).catchError((e) => debugPrint('Error in firestore auth, $e'));
});
Run Code Online (Sandbox Code Playgroud)
互联网关闭后,实时数据库需要大约 1.5 分钟才能检测到用户断开连接,我希望最多 10 秒。
客户端可以通过两种方式断开连接:
干净的断开连接,客户端让服务器知道它正在消失。
脏断开,客户端消失,由服务器检测这种情况。
对于干净的断开连接,onDisconnect您定义的写入将立即运行。
脏断开取决于套接字超时,这意味着在您的onDisconnect写入发生之前可能需要几分钟的时间。对于这种行为,您无能为力,因为它是套接字工作方式的固有部分。
如果您想要一种更快的方法来检测哪些客户端仍处于连接状态,您可以在数据库中编写一个 keep-alive。本质上:每 10 秒从每个客户端写入一个哨兵值。
| 归档时间: |
|
| 查看次数: |
2229 次 |
| 最近记录: |