Java设置socket超时时间

0

网上看了写文章,发现很多设置socket连接超时时间使用的是setSoTimeout这个方法,但这个不是设置连接超时方法,而是设置读取超时方法。

设置连接超时实在socketconnect方法,方法的最后一个参数就是连接超时参数:

    /**
     * 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);