为什么套接字在更多可用空间时读取0字节 [英] Why socket reads 0 bytes when more was available

查看:133
本文介绍了为什么套接字在更多可用空间时读取0字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现以下代码循环使用100%CPU:

  byte [] buffer = new byte [0x10000] ; 
而(true){
if(socket.Poll(5000000,SelectMode.SelectRead)== false)
继续;
int可用=套接字。可用;
,如果(可用== 0)
返回;
int读取= socket.Receive(缓冲区);
Console.WriteLine(读取: +读取+可用: +可用);
/ * ... * /
}

输出为:

 读取:0可用:1 
读取:0可用:1
读取:0可用:1
读取:0可用:1
读取:0可用:1
...

我期望socket.Receive方法读取剩余的字节,但是显然不会导致我的代码以100%循环。



由jgauffin在文档读取:


如果远程主机使用Shutdown
方法关闭
套接字连接,并且已接收到所有可用数据
,Receive方法将立即完成
返回零
个字节。


所以读0是一种期望,但是只有在读取了所有数据之后才知道是哪个套接字。 。



Socket.Available 仅提及抛出异常的封闭连接。



我如何确保最后一个字节被读取?



相关是关于如何检测依赖于套接字的关闭连接的答案。当没有更多数据并且连接关闭时,该值为0。

解决方案

您已阅读文档



读取0个字节表示远程端点已断开连接。 / p>

要么使用阻塞套接字,要么使用异步方法,例如 Beg inReceive()。 .net中不需要投票


I discovered that the following code loops with 100% CPU usage:

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);
    /* ... */
}

The output is:

Read: 0 Available: 1
Read: 0 Available: 1
Read: 0 Available: 1
Read: 0 Available: 1
Read: 0 Available: 1
...

I was expecting the socket.Receive method to read that remaining byte but it apparently doesn't resulting in my code looping at 100%.

As suggested by jgauffin the documentation reads:

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.

So reading 0 is kind of expected but only after all data is read, which socket.Available claims is not.

Documentation for Socket.Available only mention a closed connection throwing an exception.

How could I make sure that last byte is read?

Related: this is an answer of how to detect a closed connection that is dependent on the socket.Available being 0 when there is no more data and the connection is closed,

解决方案

Have you read the documentation?

0 bytes read means that the remote end point have disconnected.

Either use blocking sockets or use the asynchronous methods like BeginReceive(). There is no need for Poll in .Net.

这篇关于为什么套接字在更多可用空间时读取0字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆