java.net.SocketTimeoutException vs java.net.ConnectException

前端 未结 4 861
暗喜
暗喜 2021-01-04 20:07

When connecting to a server with a Java client socket I had this two different connection timeout exceptions.

Caused by: java.net.SocketTimeoutException: con         


        
4条回答
  •  北海茫月
    2021-01-04 20:46

    ConnectException is thrown on packet filter/firewall etc.

    SocketTimeoutException is thrown when you have set a specific timeout on your socket, and it has not received anything before the timeout.

    Example with a ServerSocket:

    ServerSocket serverSocket = new ServerSocket... // Create server socket
    serverSocket.setSoTimeout(1000);  
    serverSocket.accept();
    

    If the ServerSocket has not received anything within 1000 ms it will throw a SocketTimeoutException. Note that this exception is thrown for all sockets that use timeouts, not only ServerSocket. This means that a Socket object that throws a SocketTimeoutException hasn't got anything back from the called server before the timeout.

    To fix the problem you can either make sure that the server responds quicker, or set a higher timeout value.

提交回复
热议问题