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.
views:
37answers:
1
+3
A:
Not on the InputStream generally, but you can use Socket#setSoTimeout(int)
to set a timeout for all read operations on the socket itself.
jarnbjo
2010-04-14 14:44:14
Ah thanks, I missed that one. My only follow up question is this: this time appears to count for each time read() is called, which may be multiple times. Is there a way I can set the entire timeout time such that it it will timeout if the sum of each read() exceeds the timeout?
Zombies
2010-04-14 15:27:53
Not automatically, but you can set a shorter S0-timeout than your real timeout and check in a loop if you've exceeded your total allowed run time.
jarnbjo
2010-04-14 16:58:00
Be careful with using a socket timeout and DataInputStream together (and also a BufferredInputStream). These will buffer or read some data into temporary memory (like in getLong()) and then if the timeout occurs (waiting on more data from the socket) you will lose any of the previously read data and *there is no way to recover*. SocketTimeoutException extends InterruptedIOException which provides the number of bytes successfully transferred prior to the timeout. With a raw socket you can use this to retry/continue (perhaps to flush the bad message).
Kevin Brock
2010-04-15 03:32:38
@Zombies: probably better to create another question for your additional request.
Kevin Brock
2010-04-15 03:34:23