You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.8 KiB

import 'dart:typed_data';
/**
*
*
*
*
* 4 +body
* 2 header长度
* 2 1
* 4 15
* 4 1
* body 2048-16
* 2048
*/
class Proto {
static const int HEADER_LENGTH = 16; // 假设头部长度为16字节
static const int VERSION = 1;
int operation;
int seqId;
Uint8List body;
Proto(this.operation, this.seqId, this.body);
Uint8List toBytes() {
final buffer = BytesBuilder();
buffer.add(_intToBytes(HEADER_LENGTH + body.length, 4));
buffer.add(_shortToBytes(HEADER_LENGTH, 2));
buffer.add(_shortToBytes(VERSION, 2));
buffer.add(_intToBytes(operation, 4));
buffer.add(_intToBytes(seqId, 4));
buffer.add(body);
return buffer.toBytes();
}
static Proto fromBytes(Uint8List data) {
final buffer = ByteData.sublistView(data);
int offset = 0;
int packetLen = buffer.getInt32(offset, Endian.big);
offset += 4;
int headerLen = buffer.getInt16(offset, Endian.big);
offset += 2;
int version = buffer.getInt16(offset, Endian.big);
offset += 2;
int operation = buffer.getInt32(offset, Endian.big);
offset += 4;
int seqId = buffer.getInt32(offset, Endian.big);
offset += 4;
Uint8List body = data.sublist(offset);
return Proto(operation, seqId, body);
}
List<int> _intToBytes(int value, int length) {
final bytes = ByteData(length);
bytes.setInt32(0, value, Endian.big);
return bytes.buffer.asUint8List();
}
List<int> _shortToBytes(int value, int length) {
final bytes = ByteData(length);
bytes.setInt16(0, value, Endian.big);
return bytes.buffer.asUint8List();
}
}