当读取未完成时,读取缓冲区有问题。
如果接收到的 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
最佳答案
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);
关于c# - 如何使用 BeginReceive 接收多个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8875618/