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
73 lines
1.8 KiB
4 months ago
|
import 'dart:typed_data';
|
||
|
|
||
|
|
||
|
|
||
|
/**
|
||
|
*
|
||
|
* 需要按照格式严格封装
|
||
|
*
|
||
|
*
|
||
|
* 4个字节 放全部信息长度 头+body
|
||
|
* 2字节 header长度
|
||
|
* 2字节 默认填1
|
||
|
* 4字节 登录1,消息5
|
||
|
* 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();
|
||
|
}
|
||
|
}
|