c# - 为什么套接字在有更多字节可用时读取 0 个字节

标签 c# .net sockets

我发现以下代码会以 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,

最佳答案

你读过documentation吗? ?

0 字节读取意味着远程端点已断开连接。

要么使用阻塞套接字,要么使用像 BeginReceive() 这样的异步方法。 .Net 中不需要 Poll

关于c# - 为什么套接字在有更多字节可用时读取 0 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5868893/

相关文章:

c# - 除了 SCSS 注入(inject)还有其他选择吗? (又名穷人通过默认构造函数注入(inject))

node.js - nodejs tcp套接字发送多个数据事件

java - DataInputStream读取不阻塞

c# - 以字典作为数据源的 GridView

c# - HttpWebRequest post 返回 422 错误

c# - 如何确保控件不在面板内?

c# - 从另一个 C# 程序启动 C# 程序

c# - 同时更新多个图片框

Qt QTcpSocket : How to prevent dead lock in readyRead signal?

c# - 语音识别程序随机显示语法中不存在的那些口语词的预定义词(在 'GramarBuilder()' 中定义)