---------------------------------我们开始先写我们Tcp客户端的代码
using System;
using System.Collections.Generic;}
----------------------------------------------------------接下来我们服务器的代码----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TcpSokectSever
{
class Message
{
private byte[] data = new byte[1024];
private int startIndex = 0;//存取多少个数据
public void AddCount(int count)
{
startIndex += count;
}
public byte[] Data
{
get
{
return data;
}
}
public int StartIndex
{
get
{
return startIndex;
}
}
public int RemainSize
{
get
{
return data.Length- startIndex;
}
}
//解析数据 读取数据
public void ReadMessage()
{
while (true)
{
if (startIndex <=4)
{
return;
}
int count = BitConverter.ToInt32(data, 0);
if ((startIndex - 4) >= count)
{
Console.WriteLine(startIndex);
string s = Encoding.UTF8.GetString(data, 4, count);
Console.WriteLine("解析出来一条数据:" + s);
Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
startIndex -= (count+4);
} else
{
break;
}
}
}
}
}
------------------------------------------------------接下来我们写Message来接收消息--------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TcpSokectSever
{
class Message
{
private byte[] data = new byte[1024];
private int startIndex = 0;//存取多少个数据
public void AddCount(int count)
{
startIndex += count;
}
public byte[] Data
{
get
{
return data;
}
}
public int StartIndex
{
get
{
return startIndex;
}
}
public int RemainSize
{
get
{
return data.Length- startIndex;
}
}
//解析数据 读取数据
public void ReadMessage()
{
while (true)
{
if (startIndex <=4)
{
return;
}
int count = BitConverter.ToInt32(data, 0);
if ((startIndex - 4) >= count)
{
Console.WriteLine(startIndex);
string s = Encoding.UTF8.GetString(data, 4, count);
Console.WriteLine("解析出来一条数据:" + s);
Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
startIndex -= (count+4);
} else
{
break;
}
}
}
}
}
----------------------------这样就可以解决-----------------------------