BufferedInputStream and Blocking
-
12-01-2021 - |
Question
I am using a BufferedInputStream
to read from a socket. The BufferedInputStream
reads as follows:
socketInput.read(replyBuffer, 0, 7);
It is instantiated by
socketInput = new BufferedInputStream(mySocket.getInputStream());
mySocket
is defined as private Socket mySocket;
mySocket
is instantiated by mySocket = new Socket(ipAddress, port);
I have verified that mySocket
is connected to my device. I can send data to my device; however, I am not receiving from my device for unknown reasons but that is not the problem.
I want my BufferedInputStream
to return after say 100ms if it does not read any data. Can the BufferedInputStream
be setup to do this? Right now, it blocks indefinitely.
Solution
It's generally a bad idea to use a buffered stream for reading from a socket, for exactly this reason: it will wait forever if it doesn't see enough data to fill its internal buffer (which is going to be larger than 7 characters!) There's no way to make it time out. Just use the SocketInputStream
directly, and the problem goes away.
OTHER TIPS
Specify 100ms timeout for your socket. setSoTimeout