首页 > 解决方案 > 如何在 Dart 中读取字节数组数据?

问题描述

连接 TCP Socket 服务器并发送请求。并且服务器也在字节数组中发送响应。如何在 dart 中读取字节数组数据。

Socket.connect('localhost', 8081)
  .then((socket) {
//Establish the onData, and onDone callbacks
socket.listen((data) {
  print(new String.fromCharCodes(data).trim()); //Here data is byte[]
  //How to read byte array data

},
    onDone: () {
      print("Done");
      // socket.destroy();

    },
    onError: (e) {
      print('Server error: $e');
    });
 socket.add([255, 12, 0, 11, 0, 9, 34, 82, 69, 70, 84, 65, 72, 73, 76]);
 });
}

标签: dartflutter

解决方案


它取决于数据类型被编码为字节。假设它是String 那么你可以用dart:convert图书馆来做。

import 'dart:convert' show utf8;

final decoded = utf8.decode(data);

推荐阅读