简体   繁体   中英

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?

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).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM