首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用BeginReceive接收多个部件?

如何用BeginReceive接收多个部件?
EN

Stack Overflow用户
提问于 2012-01-16 11:55:18
回答 1查看 1K关注 0票数 2

当读取未完成时,我有读取缓冲区的问题。

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

我的代码看起来像这样:

代码语言:javascript
复制
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);
}

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

我得到了这个错误:

代码语言:javascript
复制
specified argument was out of the range of valid values. parameter name : size
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-01-16 12:13:20

代码语言:javascript
复制
  socket.BeginReceive(buffer, currentDataSize, buffer.Length, SocketFlags.None, 
                      new AsyncCallback(dataRecievedCallback), buffer);

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

代码语言:javascript
复制
  socket.BeginReceive(buffer, currentDataSize, buffer.Length - currentDataSize, SocketFlags.None, 
                      new AsyncCallback(dataRecievedCallback), buffer);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8875618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档