Flutter websocket 断开监听 [英] Flutter websocket disconnect listening
问题描述
在 Flutter 中,我想监听 websocket 断开连接事件,如何实现?当应用程序进入后台时,websocket 连接将被删除,我仍然没有找到让它在后台继续运行的方法(有人有解决方案吗?),所以我必须检测 websocket 连接是否是丢失什么的,这样我就可以在失去连接时重新连接.如果有人知道如何实现这一点,请帮忙.
In Flutter, I wanna listen to websocket disconnect event, how to achieve that? The websocket connect will be drop when app goes to background, I still not found a method to let it continuesly running in background (does anyone have solution?), So I have to detect if a websocket connect is lost or something, so that I can re-connect when lost connection. Pls help if anyone knows how to achieve that.
推荐答案
您可以通过实现 onDone
回调来查看 websocket 是否关闭.请看下面的例子:
You can find out if websocket is closed by implementing onDone
callback. See the example below:
_channel = IOWebSocketChannel.connect(
'ws://yourserver.com:port',
);
///
/// Start listening to new notifications / messages
///
_channel.stream.listen(
(dynamic message) {
debugPrint('message $message');
},
onDone: () {
debugPrint('ws channel closed');
},
onError: (error) {
debugPrint('ws error $error');
},
);
希望有所帮助.
这篇关于Flutter websocket 断开监听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!