BufferedInputStream and Blocking
Asked Answered
U

2

6

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.

Underwear answered 25/8, 2011 at 14:26 Comment(1)
If you want any kind of non-blocking or timeout I/O, you should use the NIO (java.nio) classes, not stuff in java.io.Jaguar
J
5

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.

Judicatory answered 25/8, 2011 at 14:37 Comment(2)
so you are recommending instead socket.getInputStream.read(..)?Underwear
Yes, that's it. Then you can use setSoTimeout(), as another poster suggested, and you'll get the behavior you want.Judicatory
S
5

Specify 100ms timeout for your socket. setSoTimeout

Setscrew answered 25/8, 2011 at 14:37 Comment(4)
is this still valid if I am using a BufferedInputStream?Underwear
What will happen is you'll get a SocketTimeoutException from your read() call, even though there were actually enough bytes to satisfy your request. That's not good.Judicatory
@Code Monkey it's still valid for any wrapping InputStream.Setscrew
@Ernest Friedman-Hill SocketTimeoutException throws if no data available.Setscrew

© 2022 - 2024 — McMap. All rights reserved.