连接TCP Socket服务器并发送Request。并且Server也以字节数组发送响应。如何在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]);
});
}
它取决于数据类型被编码为字节。让我们假设它是String
然后你可以用dart:convert
库来做。
import 'dart:convert' show utf8;
final decoded = utf8.decode(data);
很明显,这些字节中有一个消息结构。您举两个消息示例:
[255, 12, 0, 11, 0, 9, 34, 82, 69, 70, 84, 65, 72, 73, 76]
和
[255, 20, 0, 11, 0, 0, 0, 15, 80, 82, 69, 77, 84, 65, 72, 73, 76, 45, 53, 53, 57, 55, 48]
两者都以255开头,然后是两个或三个小端16位字(12和11)和(20,11和0)后跟一个字符串,其长度以前导字节编码。如果您希望与其他系统互操作,那么您确实需要协议规范。
假设我猜错了结构,这段代码
main() {
Uint8List input = Uint8List.fromList([
255,
20,
0,
11,
0,
0,
0,
15,
80,
82,
69,
77,
84,
65,
72,
73,
76,
45,
53,
53,
57,
55,
48
]);
ByteData bd = input.buffer.asByteData();
print(bd.getUint16(1, Endian.little)); // print the first short
print(bd.getUint16(3, Endian.little)); // and the second
print(bd.getUint16(5, Endian.little)); // and the third
int stringLength = input[7]; // get the length of the string
print(utf8.decode(input.sublist(8, 8 + stringLength))); // decode the string
}
产生
20
11
0
PREMTAHIL-55970
正如所料