How to read byte array data in Dart?

Viewed 11429

connecting TCP Socket server and sending Request. and also Server sends the response in Byte array. How to read byte array data in 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]);
 });
}
2 Answers

It depends on with data type was encoded to bytes. Let's suppose it's String Then you can do it with dart:convert library.

import 'dart:convert' show utf8;

final decoded = utf8.decode(data);

It's pretty clear that there's a message structure in those bytes. You give two examples of messages:

[255, 12, 0, 11, 0, 9, 34, 82, 69, 70, 84, 65, 72, 73, 76]

and

[255, 20, 0, 11, 0, 0, 0, 15, 80, 82, 69, 77, 84, 65, 72, 73, 76, 45, 53, 53, 57, 55, 48]

Both start with 255, followed by what looks like two or three little endian 16 bit words (12 and 11) and (20, 11 and 0) followed by a string, who's length is encoded in a leading byte. If you are expected to inter-operate with another system, you really need the protocol spec.

Assuming I've guessed the structure correctly, this code

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
}

produces

20
11
0
PREMTAHIL-55970

as expected

Related