Java – In the application, why does readInt() always throw an EOFException

exceptionjavamultithreadingnetworkingsockets

(Forgive me because I do not write in Java very often.)

I'm writing a client-side network application in Java and I'm having an interesting issue. Every call to readInt() throws an EOFException. The variable is of type DataInputStream (initialized as: DataInputStream din = new DataInputStream(new BufferedInputStream(sock.getInputStream())); where sock is of type Socket).

Now, sock.isInputShutdown() returns false and socket.isConnected() returns true. I'm assuming that this means that I have a valid connection to the other machine I'm connecting to. I've also performed other checks to ensure that I'm properly connected to the other machine.

Is it possible that the DataInputStream was not set up correctly? Are there any preconditions that I have missed?

Any help is greatly appreciated.


@tofubeer: I actually wrote 17 bytes to the socket. The socket is connected to another machine and I'm waiting on input from that machine (I'm sorry if this was unclear). I successfully read from the stream (to initiate a handshake) first and this worked just fine. I'm checking now to see if my sent-requests are malformed, but I don't think they are. Also, I tried reading a single byte from the stream (via read()) and it returned -1.

Best Solution

Are you writing 4 bytes to the socket? According to the JavaDoc it will throw an EOFException if this stream reaches the end before reading all the bytes.

Try calling readByte() 4 times in a row instead of readInt() and see what happens (likely not all of them will work).

Edit (given your edit).

Find out how many times you can call read() before you get the -1.

When read() returns -1 it means that it has hit the end of file.

Also find out what each read() returns to make sure what you are reading in is what you actually wrote out.

It sounds like a problem either with the read code reading more than you thing while doing the handshake or the other side not writing what you think it is writing.