简体   繁体   中英

Java socket timeout does not apply

I have this socket implementation in java which uses timeout:

        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(ip, port), 5000);

        } catch (SocketException e2) {
            System.out.println("Something wrong with the socket: " + e2);
        }

The ip and port is closed, so connection cannot be made. But the timeout here does not work. It does not wait for 5 seconds and then return an error.

This code is located in constructor and calls from runnable class. May this be the reason?

The connect timeout is the maximum time that connect() will block for. If there is an immediate connection refusal or other error, you will get it immediately. In this case the target port wasn't listening so you would have got an immediate ConnectException: connection refused . It isn't obliged to wait for the timeout if the error happens sooner. The timeout is really for where there is no response at all. Waiting after an error doesn't make any sense.

Socket socket = new Socket();

// This limits the time allowed to establish a connection

// timeout takes place if connection result is not received with in the specified timeout.

socket.connect(new InetSocketAddress(host, port), timeout);

// This stops the request for waiting for response after connection succeeds.

socket.setSoTimeout(timeout);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM