class Message
{
//发送信息
public byte[] SendData(byte[] message)
{
MemoryStream memoryStream = new MemoryStream();//创建一个内存流
byte[] BagHead = BitConverter.GetBytes(message.Length + 4);//往字节数组中写入包头(包头自身的长度和消息体的长度)的长度
memoryStream.Write(BagHead, 0, BagHead.Length);//将包头写入内存流
memoryStream.Write(message, 0, message.Length);//将消息体写入内存流
byte[] HeadAndBody = memoryStream.ToArray();//将内存流中的数据写入字节数组
memoryStream.Close();//关闭内存
memoryStream.Dispose();//释放资源
return HeadAndBody;
}
//接收信息
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
public void ReceiveData(byte[] receivedata, int receiveLength)
{
memoryStream.Write(receivedata, 0, receiveLength);//将接受到的数据写入内存流中
byte[] getData = memoryStream.ToArray();//将内存流中的消息体写入字节数组
int StartIndex = 0;//设置一个读取数据的起始下标
while (true)
{
if (receiveLength > 0)//如果接受到的消息不为0(不为空)
{
int HeadLength = 0;//包头长度(包头+包体)
if (getData.Length - StartIndex < 4)//包头接受不完整
{
HeadLength = -1;
}
else
{
//如果包头接受完整 转换成int类型的数值
HeadLength = BitConverter.ToInt32(getData, StartIndex);
}
//包头接受完整但是消息体不完整 //包头接受不完整
//↓↓↓↓↓↓↓↓ ↓↓↓
if (getData.Length - StartIndex < HeadLength || HeadLength == -1)
{
memoryStream.Close();//关闭内存流
memoryStream.Dispose();//释放内存资源
memoryStream = new MemoryStream();//创建新的内存流
memoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
break;
}
else
{
//如果消息(包头+包体)接受完整了,解析数据
string str = Encoding.UTF8.GetString(getData, StartIndex + 4, HeadLength - 4);
Console.WriteLine("接收到客户端的消息是-----"+HeadLength+" " + str);
StartIndex += HeadLength;//当读取一条完整的数据后,读取数据的起始下标应为当前接受到的消息体的长度(当前数据的尾部或下一条消息的首部)
}
}
}
}
}