Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

c# - Why socket reads 0 bytes when more was available

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,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...