How to make readInt () block on input byte stream?

I have an input stream coming from a black box (say B). All messages coming from this stream are serialized binary data, and each message starts with a four-byte int. Most of them register data and work 24 hours a day. I read these four bytes using the readInt () method. Now, sometimes, the main thread exited with an EOFException and crashed the program.

After examining this, I found that this happens when there are less than four bytes in the input stream during readInt (). I assume that the buffer does not fill up fast enough between consecutive readings. Some of the possible solutions that I think of include checking for available () before reading (consumes too many cycles based on the amount of data) or restarting when an exception occurs (this sounds like poor programming). If I could block the use of readInt (), that would be the best way, I think. I looked at the implementation of readInt (), but again it comes down to blocking with read ().

Does anyone know of a better solution?

+3
source share
3 answers

"", , . readInt DataInputStream read , , , , , " ", .

, , , -1 . - /? ?

+1

, DataInputStream. EOFException , , , -1 read() ( , ).

, , -1 .

+1

InputStream , EOFException, readInt() , int , E nd O f F ile.

EOFException - , , . , " " .

Since the stream is network-based, your socket may have a timeout set, if so, try changing the SOTimeout socket value .

0
source

Source: https://habr.com/ru/post/1789770/


All Articles