接收比较麻烦点,因为不知道要接收多少,我们可以分段接收,然后重组
public struct ReceiveBuffer
{
Socket sock;
pubic Queue<byte[]> data;
public byte[] buff;
public int count;
public int totallength;
}
public void Receive(ReceiveBuffer b)
{
// 准备接收数据
b.buff = new byte[1024];
b.count = 0;
if (b.data.Count==0)
b.totallength = 0;
// 开始接收
b.sock.BeginReceive(b.buff, 0, b.buff.Length, SocketFlags.None,
new AsyncCallback(EndReceiveCallback), b)
}
private void EndReceiveCallback(IAsyncResult ar)
{
ReceiveBuffer b = (ReceiveBuffer)ar.AsyncState;
b.count = b.EndReceive(ar);
if (b.Length>b.count)
{
byte[] shallow = new byte[b.count];
for(int i=0; i<b.count; i++)
{
shallow[i]=b.buff[i];
}
b.data.Enqueue(shallow);
}
else
{
b.data.Enqueue(b.buff);
}
b.totallength += b.count;
if (b.sock.Available>0)
Receive(b);
}