1, the Socket class construction method is many, only the parameterless construction method does not attempt to establish the connection, the other constructs the method, will attempt to establish the connection, if establishes the connection to fail, will throw the exception. If you want to set the connection time-out for the socket, you need to use the parameterless construction method as follows:
Everyone may be a little strange, set the timeout time is obviously 1ms, why spent 2ms after the establishment of a successful connection, rather than report timeout exception. Looking at the comments in the code, it is clear that the time-out is three handshake time. Besides, the time is not counted. If you close the server and run the program again, you will get an error: Exception in thread "main" is java.net.SocketTimeoutException:connect timed out.
If you enlarge the time of the three handshake (the server is stopped), look at the following result:
At this point, the exception is not timed out. This shows that the network in the establishment of the connection, there will be a small time to confirm that the network is not, if in this time frame, the network has been a non-pass, he thought the network is not through. The above exception will occur.
If you set the time-out to a smaller number, the following results appear:
This shows that, 100s this time is not enough to confirm that the network is not connected, in other words, 100ms is not to confirm the network does not pass the maximum time, so, still trying to establish a connection, so burst connection timeout.
The use of JAVA socket non-parametric construction method