c#中tcp 通讯消息把包长定义到发送数据中 [msg.length,data]方式的实现
参考:
https://blog.csdn.net/weixin_42033401/article/details/81558391
client或者server发送的规则
public void Send(string str)
{
//2.把消息长度封装在消息中
byte[] data = Encoding.UTF8.GetBytes(str);
byte[] head = BitConverter.GetBytes(data.Length+4);
byte[] msg = head.Concat(data).ToArray();
socket.Send(msg);
}
client或者server接收的规则
//用来存储接收的缓存
private byte[] ReceiveBuf = new byte[1024];
//提前声明的缓存区
byte[] surplusBuffer = null;
public void ReceiveMeg(int len, byte[] recBuffer)
{
byte[] data;
int StartIndex = 0;
if (surplusBuffer == null)
{
data = new byte[len];
Array.Copy(recBuffer, data, len);
}
else
{
data = surplusBuffer.Concat(recBuffer).ToArray();
len += surplusBuffer.Length;
surplusBuffer = null;
}
while (true)
{
//如果接受到的消息不为0(不为空)
int HeadLength = 0;//包头长度(包头+包体)
if (data.Length - StartIndex < 4)//包头接受不完整
{
HeadLength = -1;
}
else
{
//如果包头接受完整 转换成int类型的数值
HeadLength = BitConverter.ToInt32(data, StartIndex);
}
//包头接受完整但是消息体不完整 //包头接受不完整
//↓↓↓↓↓↓↓↓ ↓↓↓
if (data.Length - StartIndex < HeadLength || HeadLength == -1)
{
surplusBuffer = new byte[data.Length - StartIndex];
Array.Copy(data, StartIndex, surplusBuffer, 0, data.Length - StartIndex);
break;
}
else
{
//如果消息(包头+包体)接受完整了,解析数据
string str = Encoding.UTF8.GetString(data, StartIndex + 4, HeadLength - 4);
Debug.Log("接收到客户端的消息是-----" + str);
StartIndex += HeadLength;//当读取一条完整的数据后,读取数据的起始下标应为当前接受到的消息体的长度(当前数据的尾部或下一条消息的首部)
if (StartIndex >= len)
{
break;
}
}
}
}
2.再补充一个定长的实现方案
client
发送消息
public void Send(string str)
{
byte[] data = Encoding.UTF8.GetBytes(str);
data.CopyTo(ReceiveBuf, 0);
socket.Send(ReceiveBuf);
}
server
接收消息
string str = Encoding.UTF8.GetString(ReceiveBuf, 0, ReceiveBuf.Length);
// string str2 = BitConverter.ToString(ReceiveBuf, 0);
Array.Clear(ReceiveBuf, 0, 1024);
int lenth = 0;
for (int i = 0; i < 1024; i++)
{
if (str[i] != '\0')
{
lenth += 1;
}
else
{
break;
}
}
string str2 = str.Substring(0,lenth);
Debug.Log(str2 +"--------"+str2.Length);
StartReceive();