Reputation: 923
I've got a thread that opens a socket that sends data to a server. The server may send data back depending if someone is at the work station. However I'm trying to put a timeout on the BufferedReader
so that after 30 seconds it continues saying the response was null.
//Receive Response
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
response = new StringBuilder();
while ((line = bufferedReader.readLine()) != null ) {
response.append(line);
}
This is my BufferedReader
, pretty standard, I've looked at a bunch of timers and other posts but haven't found a working solution.
Upvotes: 3
Views: 1727
Reputation: 19427
You could call setSoTimeout()
on your socket instance.
Itt will raise a SocketTimeoutException
when the timeout is reached. Wrap your reading logic in a try-catch block, catch that exception and handle it as you wish.
Something like this:
try {
socket.setSoTimeout(30000);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((line = bufferedReader.readLine()) != null ) {
response.append(line);
}
} catch (SocketTimeoutException ste) {
// timeout reached
} catch (Exception e) {
// something else happened
} finally {
// some general processing
}
Upvotes: 3