1.构建消息包类 MessagePackage
<1> 定义包头
根据业务需求,这里有5种:
// 构造包头用的数据(包头10个字节里的内容)
public int bufferSize = 0;// 消息总长度
public int protocolId = 0;// 消息ID
// 网络标记包用来标记消息是否压缩、加密等信息 比如:0表示无压缩 无加密
public ushort nFlags = 0;
public ushort nModuleId = 0;// 发送的模块Id 客户端和服务器之间通讯设置为0
public uint bodyLength = 0;// 包体长度
<2> 接受数据缓冲区 和 当前接受包接受字节多少的索引
public byte[] buffer;
public int bufferPoint;// 用来指示当前已经接收了多少字节
<3>自定义构造方法(用来初始化buffer区和重置bufferPoint)
上代码:
public MessagePackage(int size) {
CreatBuffer(size);
}
public void CreatBuffer(int size) {
buffer = new byte[size];
bufferPoint = 0;
}
<4>将数据包头信息转换为实际信息
#region 将数据包头信息转换为实际信息
// 将字节数组(长度为2)转换成数字
private ushort BytesToInt(byte[] bytes) {
int value = 0;
value |= (bytes[1] & 0xFF) << 8;
value |= (bytes[0] & 0xFF);
return (ushort)value;
}
// 重置字节数组依次取出n个字节出来
private byte[] GetBytes(byte[] byteArr, int length, int offset) {
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
{
bytes[i] = byteArr[offset + i];
}
return bytes;
}
// 读取包头信息
public void ReadPacketHead(MessagePackage msg) {
bodyLength = BytesToInt(GetBytes(msg.buffer, 2, 0));
bufferSize = BytesToInt(GetBytes(msg.buffer, 2, 2));
mouduleId = BytesToInt(GetBytes(msg.buffer, 2, 4));
flags = BytesToInt(GetBytes(msg.buffer, 2, 6));
protocolId = BytesT