我发现以下代码会以 100% 的 CPU 使用率循环:
byte[] buffer = new byte[0x10000];
while (true) {
if (socket.Poll (5000000, SelectMode.SelectRead) == false)
continue;
int available = socket.Available;
if (available == 0)
return;
int read = socket.Receive (buffer);
Console.WriteLine ("Read: " + read + " Available: " + available);
/* ... */
}
输出是:
Read: 0 Available: 1
Read: 0 Available: 1
Read: 0 Available: 1
Read: 0 Available: 1
Read: 0 Available: 1
...
我期待 socket.Receive 方法读取剩余的字节,但它显然不会导致我的代码以 100% 循环。
正如 jgauffin 所建议的 documentation阅读:
If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.
所以读取 0 是一种预期,但只有在读取所有数据之后,而 socket.Available 声明不是。
Socket.Available 的文档只提到一个关闭的连接抛出异常。
我如何确保读取到最后一个字节?
相关: this是如何检测依赖于套接字的关闭连接的答案。当没有更多数据并且连接关闭时,Available 为 0,
最佳答案
关于c# - 为什么套接字在有更多字节可用时读取 0 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5868893/