The bytes my server program receives is incomplete. Why? I'm using C# .net sockets

我的梦境 提交于 2019-12-02 04:21:07

If Available is zero this does not mean that you have finished reading bytes. It means that currently, in this nanosecond, there are no bytes queued. How could the server know how many bytes will be coming in the future?

In good approximation, every singe use of Available is an error!

Delete all usages of Available. Instead, always try to read a full buffer. If you get 0 this means the socket has been closed and you are done.

Edit: Here is some canonical read code:

var buffer = new byte[8192];
while(true) {
 var readCount = stream.Read(buffer, 0, buffer.Length);
 if (readCount == 0) break;
 outputStream.Write(buffer, 0, readCount);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!