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

标签 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

最佳答案

  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/

相关文章:

c# - 将 JSON 对象反序列化为数组

c# - EPplus插入X个空行

c# - 在 Python 中与 Arduino : works in C#, 对话失败

c# - 更整洁的 GetType().ToString() 用于封闭泛型

c# - 基于功能区的 GUI - Winforms 与 WPF

c# - 使用 Mysql 和 C# 通过报表查看器创建报表

javascript - jquery 点击功能不起作用

c# - 在 asp net mvc 5 中使用 session 变量进行授权

c# - 如何在 msbuild 内联任务中使用 C#6 语法?

c# - 客户端配置文件错误