Afshin Moazami
Afshin Moazami

Reputation: 2098

Java program and network connection timeout

I have a java program that gather data from the web. Unfortunately, my network has a problem and it goes off and on.
I need a trick to ask my program wait until the connection is on again and continue its job.
I use the "URLConnection" library to connect. I made a loop to reconnect when it a "ConnectException" is catched, but it doesn't work.
Any suggestions?

Upvotes: 0

Views: 812

Answers (1)

Cratylus
Cratylus

Reputation: 54074

my network has a problem and it goes off and on. I need a trick to ask my program wait until the connection is on again and continue its job

It depends on what your program's purpose is.
How long are these intermittent failures? If they are short enough you could use setConnectTimeout(0) to indicate an infinite timeout period while trying to connect but if your program has to report something back then it is not a good option for the end user.
You could set a relatively low timeout so that when you start to lose the network you will get a java.net.SocketTimeoutException.
When you catch this, you could wait for a period and try again in a loop e.g. for 3 times and then perhaps report a failure.
It depends on what you are trying to do.

Upvotes: 1

Related Questions