0

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Okay, then how could I do that it will wait for some maximum time and then return an error despite of closed port or not? May be it will be opened while waiting this timeout?
You can't. Try a loop, with sleeps.
0

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

6 Comments

Doesn't answer the question.
timeout in socket.connect means connection will timeout if it cannot connect within a certain time.
setSoTimeout specifies the time in which to disconnect if no reponse is received.
Just repeating yourself adds nothing to your answer, which still doesn't answer the question. He knows that, and he is already doing it. The question here is why he didn't get a timeout.
Because he is getting the connection result before 5 seconds.So the timeout did not take place.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.