如何使用BeginReceive接收多个部分?

时间:2012-01-16 03:55:18

标签: c#

读取缓冲区时,我没有问题。

如果收到的XML数据有效,那我就没问题了。但是当收到的XML数据不正确时,我正在等待数据的第二部分,并且我得到一个错误。

我的代码如下:

int currentDataSize = socket.EndReceive(iar);
string currentData  = convertToString(buffer, currentDataSize);

if (IsValidXml(currentData))
{
  //Here I am parsing the xml data and writing into the sql db.
  runParseWorker(currentData);      

  //Here I am sending the xml-data to all clients.
  runSendWorker(currentData);

  //Here I am calling the BeginRecieve Method again.
  socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, 
                      new AsyncCallback(dataRecievedCallback), null);
}
else
{ 
  //It gives error when I use offset..
  socket.BeginReceive(buffer, currentDataSize, buffer.Length, SocketFlags.None, 
                      new AsyncCallback(dataRecievedCallback), buffer);
}

如何获取其余数据以及如何正确使用偏移?

我收到此错误:

specified argument was out of the range of valid values. parameter name : size

1 个答案:

答案 0 :(得分:2)

  socket.BeginReceive(buffer, currentDataSize, buffer.Length, SocketFlags.None, 
                      new AsyncCallback(dataRecievedCallback), buffer);

如果使用偏移量,您收到的数据将从指定的偏移量开始存储在缓冲区中,因此您需要一个大小偏移+长度的数组。在您的情况下,只需调整长度以正确指示您可以存储的字节数(buffer.Length - currentDataSize):

  socket.BeginReceive(buffer, currentDataSize, buffer.Length - currentDataSize, SocketFlags.None, 
                      new AsyncCallback(dataRecievedCallback), buffer);