Java设置socket超时时间

网上看了写文章,发现很多设置socket超时时间使用的是:setSoTimeout这个方法,但这个不是设置超时方法,具体的作用自己google一下。

socket有一个connect的方法,里面的最后一个参数就是超时的参数:

    /**
     * Connects this socket to the server with a specified timeout value.
     * A timeout of zero is interpreted as an infinite timeout. The connection
     * will then block until established or an error occurs.
     *
     * @param   endpoint the <code>SocketAddress</code>
     * @param   timeout  the timeout value to be used in milliseconds.
     * @throws  IOException if an error occurs during the connection
     * @throws  SocketTimeoutException if timeout expires before connecting
     * @throws  java.nio.channels.IllegalBlockingModeException
     *          if this socket has an associated channel,
     *          and the channel is in non-blocking mode
     * @throws  IllegalArgumentException if endpoint is null or is a
     *          SocketAddress subclass not supported by this socket
     * @since 1.4
     * @spec JSR-51
     */
    public void connect(SocketAddress endpoint, int timeout) throws IOException {

所以代码这样写:

Socket socket = new Socket();
socket.connect(new InetSocketAddress("ip", port), 4 * 1000);