【问题标题】:How to handle websocket with dart:io Flutter如何使用 dart:io Flutter 处理 websocket
【发布时间】:2021-10-08 10:22:23
【问题描述】:

我想避免使用 web_socket_channel 包,尽管它的投票似乎没有得到积极维护(许多 github 问题没有得到解答)并且不处理错误。

我只需要从 Flutter 连接到我在 AWS 中的 WebSocket API。

我如何使用dart:io 包做到这一点?或者 socket_io_client 可以吗?我看到连接是与http 而不是wss

【问题讨论】:

    标签: flutter dart websocket


    【解决方案1】:

    除了通常的 try - catch 之外,我还找到了一种方法来使用 web_socket_channel 包处理 channel.sink.listen StreamSubscription 对象中的错误。

    你可以根据这个answer做如下操作:

     _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');
            },
          );
    

    这确实有效,当然在我的用例中不需要使用 SocketIO。

    【讨论】:

      猜你喜欢
      • 2020-01-26
      • 2014-04-02
      • 2020-12-14
      • 2015-02-28
      • 2018-07-16
      • 2021-10-02
      • 2016-08-01
      • 2015-10-25
      • 2021-12-06
      相关资源
      最近更新 更多