How to set timeout on BufferedReader and printwriter in Java 1.4?

How do I set timeouts in BufferedReader and printwriter created using socket connections? This is my code for the server until the server or client crashes:

while(isReceiving){
                    str = null;
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);


                    while ((str = br.readLine()) != null){
                        System.out.println("Processing command " + str);
                        pw.println(client.message(str));
                    }
                }

Outside the scope of this code, I have imposed a socket timeout of 1000ms, which works normally while waiting for the initial connection But the program is blocked in (STR = br. Readline()) If the client hangs or crashes, it will never stop blocking unless I terminate the process (even if it doesn't always work)

The client code is very similar to this and blocks it in a similar way

Solution

You can use Google guava Library's simpletimelimiter

Sample code (in Java 8):

BufferedReader br = ...;
TimeLimiter timeLimiter = new SimpleTimeLimiter();

try {
    String line = timeLimiter.callWithTimeout(br::readLine,10,TimeUnit.SECONDS);
} catch (TimeoutException | UncheckedTimeoutException e) {
    // timed out
} catch (Exception e) {
    // something bad happened while reading the line
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>