0

我正在尝试捕获 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)
4

1 回答 1

0

要么这不是真正的代码,要么你在某处有自己的 SocketTimeoutException 类,要么你导入了错误的类。我建议你在 catch IOException 块中加入一些有用的东西。你可能会得到一个惊喜。

为什么您要捕获 AssertionError 并将其视为超时对我来说是个谜。

于 2014-06-01T02:02:30.017 回答