【问题标题】:Get data from TCP Socket withost using listen() in Flutter在 Flutter 中使用 listen() 从 TCP Socket 获取数据
【发布时间】:2020-08-24 06:19:07
【问题描述】:

我需要一种方法来从我制作的 TCP Java 服务器检索数据(在 Flutter 应用程序内),但不使用 Socket 方法 socket.listen()。我想要像socket.read() 这样可能返回Future<Uint8List> 的东西,所以我可以等待。有这样的东西吗?

【问题讨论】:

    标签: sockets flutter dart tcp async-await


    【解决方案1】:

    即使存在这样的方法(顺便说一下,RawSocket 有这样的功能,但它是非阻塞的,并且只会返回可用的 - 可能是零字节)你仍然会遇到一些问题。

    未来将以任意数量的字节完成,这可能不是整个消息,因此您必须保存这些字节并等待更多。

    可能更重要的是,您将如何使用这种方法?也许是这样?

    Future<Uint8List> readBytes() async {
      return await _socket.read(); // NB no such method really exists
    }
    

    但是你如何使用它呢?

    readBytes().then((bytes) {
      // process the bytes
    });
    

    但是,这并不比

    简单
    socket.listen((bytes) {
      // process the bytes
    });
    

    也许你可以解释一下你不喜欢listen 的地方,或者你为什么不能使用它。请记住,您可能在 Java 中使用的阻塞读取通常在后台线程上完成,而 Dart 中没有。

    【讨论】:

      猜你喜欢
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      • 2020-06-07
      • 2021-07-04
      • 2021-02-03
      相关资源
      最近更新 更多