I have a DataInputStream
that I obtained from a Socket
. Is there any way I can set a timeout for dis.read(...)
? Currently I spawn a new thread to do the read. While the parent thread does a thread.join(timeout)
to wait before interrupting it. I am aware of nio, but I don't think I want to refactor that much at this point. Thanks.
It's meaningless for it to have available data. Hence, javadoc for available() also states: The available method for class InputStream always returns 0.
Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code: String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket. setSoTimeout(10*1000);
Not on the InputStream generally, but you can use Socket#setSoTimeout(int)
to set a timeout for all read operations on the socket itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With