How can we find that all bytes receive from sockets?

橙三吉。 提交于 2019-12-01 13:34:36

While the socket is open, there is no way of doing this without causing it to block when it reaches the end (expecting more data).

There are several ways of doing it:

  • close the socket after sending
  • have some marker that means "end of message" (easy enough with encoded text - 0 being a common choice; tricky when sending arbitrary binary data, though)
  • send a length prefix before the data (100,000 in this case), and stop reading when you get that much

If it was a NetworkStream, for example, using a length prefix:

int expecting = //TODO: read header in your chosen form
int bytesRead;
while(expecting > 0 && (bytesRead = stream.Read(buffer, 0,
        Math.Min(expecting, buffer.Length))) > 0)
{
    // TODO: do something with the newly buffered data
    expecting -= bytesRead;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!