44

I am trying to set the timeout of a connection on the client socket in Java. I have set the connection timeout to 2000 milliseconds, i.e:

this.socket.connect(this.socketAdd, timeOut);

This I am trying on a web application. When a user makes a request, I am passing values to socket server, but if I don't receive any response in 5 secs the socket should disconnect.

But in my case the whole request is getting submitted once again. Can any one please tell me where am I going wrong?

I want to cut the socket connection, if I don't get any response in 5 secs. How can I set it? Any sample code would help.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Vardhaman
  • 899
  • 3
  • 11
  • 10

3 Answers3

63

You can try the follwoing:

Socket client = new Socket();   
client.connect(new InetSocketAddress(hostip, port_num), connection_time_out); 
informatik01
  • 16,038
  • 10
  • 74
  • 104
xyz
  • 2,160
  • 3
  • 20
  • 31
37

To put the whole thing together:

Socket socket = new Socket();
// This limits the time allowed to establish a connection in the case
// that the connection is refused or server doesn't exist.
socket.connect(new InetSocketAddress(host, port), timeout);
// This stops the request from dragging on after connection succeeds.
socket.setSoTimeout(timeout);
anisbet
  • 2,662
  • 2
  • 20
  • 12
20

What you show is a timeout for the connection, this will timeout if it cannot connect within a certain time.

Your question implies you want a timeout for when you are already connected and send a request, you want to timeout if there is no response within a certain amount of time.

Presuming you mean the latter, then you need to timeout the socket.read() which can be done by setting SO_TIMEOUT with the Socket.setSoTimeout(int timeout) method. This will throw an exception if the read takes longer than the number of milliseconds specified. For example:

this.socket.setSoTimeout(timeOut);

An alternative method is to do the read in a thread, and then wait on the thread with a timeout and close the socket if it timesout.

Gray
  • 115,027
  • 24
  • 293
  • 354
Jim Morris
  • 2,870
  • 24
  • 15
  • 1
    Does "soTimeout" consider TCP acks? Let's say I send some data at time 't' and receive an acknowledgement from server at time 't' + 10. Nothing is received from the server after this ack. If "soTimeout" was set to 20 on my client , then will TCP layer consider the connection as closed at 't'+20 or at 't'+30. – kunjbhai Jun 19 '19 at 13:07
  • In case TCP will consider the connection closed at 't'+20 then yes setting "soTimeout" is same as reading on separate thread and timing out the thread otherwise it's not. This distinction is important as in case of TCP keep-alive acks are sent by server periodically to keep the connection alive. read from socket will never return because of keep-alive ack packets and so a tcp connection might break despite connection being active with server. – kunjbhai Jun 19 '19 at 13:17