0

I implemented a REST client using HttpURLConnection. The problem is when I do a particular actions on the server, the server may temporally goes out of the network and comes back in a while. But the client expects response and it waits at conn.getInputStream() till the time out. The thread waits even after the server came to network back.

Is there any way I can understand when a server goes out of reach while a connection is enabled?

Sample code:

PrintWriter out = new PrintWriter(conn.getOutputStream(), true);
out.println(data);
....
    response.append(convertInputStreamContentToString(conn.getInputStream()));
.....
Kajal
  • 709
  • 8
  • 27
  • "the server may temporally goes out of the network and comes back in a while" - Do you mean it literally is not accessible on the network by any device for this time? It sounds like a problem with your server, not your code. However, you should be getting an IOException at least. – Steve Smith Jan 27 '17 at 10:29
  • this may help http://stackoverflow.com/questions/10240694/java-socket-api-how-to-tell-if-a-connection-has-been-closed – Shubham Chaurasia Jan 27 '17 at 10:33
  • @ShubhamChaurasia, Thank you for the response. I am facing the challenge at the point number 5(If the peer is still connected but not using the connection, a read timeout can be used). Is there any way i can know when the peer(server here) not using the connection anymore ? – Kajal Jan 27 '17 at 13:11
  • @steveSmit That is an expected behaviour. The client send command to execute in the server. That may disable the connection for a while – Kajal Jan 27 '17 at 13:11
  • @Kajal yes. Configure timeout of socket which would raise a `java.net.SocketTimeoutException` if the timeout expires. – Shubham Chaurasia Jan 27 '17 at 13:25
  • It sounds like the server is simply taking a long time to respond, rather than "going out of the network" or "disabling the connection". – Steve Smith Jan 27 '17 at 14:20

0 Answers0