有没有一种方法可以使Firebase实时数据库存在系统更快地检测到断开连接
问题内容:
我正在创建一个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'));
});
互联网断开后,实时数据库大约需要1.5分钟才能检测到用户已断开连接,我希望此时间最多为10秒。
问题答案:
客户端可以通过两种方式断开连接:
-
干净的断开连接,客户端让服务器知道它正在消失。
-
肮脏的断开连接,客户端消失,由服务器来检测这种情况。
对于完全断开连接,onDisconnect
您定义的写入将立即运行。
肮脏的断开连接取决于套接字超时,这意味着可能要花费几分钟才能进行onDisconnect
写操作。对于此行为,您无能为力,因为它是套接字工作方式的固有部分。
如果您想要一种更快的方法来检测哪些客户端仍在连接,则可以在数据库中编写一个保持活动状态。本质上:每10秒从每个客户端写入一个哨兵值。