miloserdow
miloserdow

Reputation: 1087

Why does Java read the same byte from broken socket over and over again?

The client reads the status byte in the loop while it is equal to 0x01:

do {
    input.read(magicWord); // ALWAYS THE SAME BYTE AFTER THE SERVER IS GONE
    if (magicWord[0] == (byte) 0xFF)
        break;

    // retrieve the progress
    byte[] cur = new byte[4];
    input.read(cur);

    // and set the progress bar
    progressBar.setValue(ByteBuffer.wrap(cur).getInt());
} while (!isCancelled());

But if the server crashes (for example by SIGKILL) while the client is in this loop, the client keeps getting the last magickWord sent by the server over and over again (and gets into the endless loop). Even setting SO_TIMEOUT doesn't solve the problem. How should the client detect a server failure?

Upvotes: 0

Views: 50

Answers (3)

GhostCat
GhostCat

Reputation: 140623

That call to read returns the number of bytes read. You do not check that result.

And you do not clear your read buffer - thus you keep seeing the same bytes all the time.

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41686

Your code is wrong.

You must check the return value of the read call. Look it up in the documentation and write your code accordingly.

Upvotes: 0

talex
talex

Reputation: 20542

It doesn't read anything at all. input.read(magicWord) return -1. You 0xFF byte in your buffer since previous read (read method doesn't clear buffer).

Upvotes: 3

Related Questions