如何在BufferedReader和使用套接字连接创建的PrintWriter设置超时?这是我现在对服务器的代码,直到服务器或客户端崩溃:
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)); } }
在此代码范围之外,我已经施加了1000ms的套接字超时,这在等待初始连接时正常工作.但程序阻塞在(str = br.readLine()).如果客户端挂起或崩溃,它永远不会停止阻止,除非我终止进程(即使不总是工作).
客户端代码与此非常相似,并以类似的方式阻止.
解决方法
您可以使用Google Guava图书馆的
SimpleTimeLimiter.
示例代码(在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 }