我正在尝试捕获 SocketTimeoutException,以便我的套接字保持活动状态,并且我可以继续阅读我的程序。不幸的是,无论我如何尝试捕捉读取超时,我都无法捕捉到,因此应用程序关闭了。
我有一个套接字并将超时设置为 30000。
我调用 input.readLine() 并想赶上超时并继续。任何帮助深表感谢。
String response;
try {
response = input.readLine();
System.out.println("Server Response: " + response);
return;
} catch(AssertionError e){
//we timed out. print to user that timeout occured,
//try command again
System.out.println("TIMEOUT: Please try your command again.\n"
+ "If you created a game, join an existing or create again.");
} catch (SocketTimeoutException e) {
//we timed out. print to user that timeout occured,
//try command again
System.out.println("TIMEOUT: Please try your command again.\n"
+ "If you created a game, join an existing or create again.");
} catch (IOException ex) {
//do nothing
}
输出是:
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:150)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at Client.main(Client.java:97)