本文介绍了Flutter WebSocket断开监听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 回调。参见下面的示例:

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断开监听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:55