java_net_SocketTimeoutException

问题分析

这类异常发生在建立socket连接或读取数据时发生超时时抛出。

解决方案

SocketTimeoutException发生在socket连接过程中的accept()read()中,服务端或客户端设置超时连接后,当到达超时时间均会抛出此类异常。建议设置可接受的socket超时时间并捕获处理SocketTimeoutException。

代码示例

服务器端:

    ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8111);
            serverSocket.setSoTimeout(10000);
            while (true) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    System.out.println("Client said :"+ inputReader.readLine());
                } catch (SocketTimeoutException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

客户端:

@Override
public void run() {
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        con.setConnectTimeout(5000);
        log.info("Response Code: " + con.getResponseCode());
    } catch (SocketTimeoutException e) {
        System.out.println(“SocketTimeoutException”+e.getMessage());
    } catch (IOException e) {
        System.out.println(“IOException”+e.getMessage());
    } catch (Exception e) {
        System.out.println(“Exception”+e.getMessage());
    }
}

参考文献