Makky
Makky

Reputation: 17463

Socket Timeout is not working in Servlet

I have a Java servlet which tries to connect to the source(Using request ip address).

Method is as :

String ip = request.getRemoteAddr();

private void connect(String ip) throws SocketException, IOException {
        Socket socket = new Socket();
        socket.setSoTimeout(1000);
        socket.connect(new InetSocketAddress(ip, Constant.PORT));
    }

Now if it doesn't connect withint a second it should throw exception but it is not throwing exception in one second but takes a while like 10-15 seconds.

Could someone help why this is happening?

Upvotes: 2

Views: 1488

Answers (1)

Aleksander Blomskøld
Aleksander Blomskøld

Reputation: 18542

SO_TIMEOUT (which is set by socket.setSoTimeout) only affects socket.getInputStream().read(). To specify connect timeout, specify a second parameter to socket.connect:

socket.connect(new InetSocketAddress(ip, Constant.PORT), 1000);

Upvotes: 6

Related Questions