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

后端 未结 1 1936
没有蜡笔的小新
没有蜡笔的小新 2021-01-25 03:15

This doesn\'t always happen. But it happens more often than receiving the bytes completely.

This is how my client prog sends bytes to my server prog:

pub         


        
相关标签:
1条回答
  • 2021-01-25 03:41

    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);
    }
    
    0 讨论(0)
提交回复
热议问题