Right now I'm doing this:
while (true) {
try {
SocketAddress sockaddr = new InetSocketAddress(ivDestIP, ivDestPort);
downloadSock = new Socket();
downloadSock.connect(sockaddr);
this.oos = new ObjectOutputStream(downloadSock.getOutputStream());
this.ois = new ObjectInputStream(downloadSock.getInputStream());
break;
} catch (Exception e) {}
}
downloadSock.connect(sockaddr)
will generate a ConnectionRefused
exce开发者_开发技巧ption if the remote host is not listening on the socket. I'm running my code in a separate thread, so I'm not worried about blocking. Given this, is my method of retrying appropriate or is there a better way???
Thanks!
Its OK to try to attempt to connect to a remote server in a loop, and is actually very common, but make sure that there's a Thread.sleep(ms)
in each iteration, or, the server host may think that you are trying a DOS.
In this case I usually use a progressively longer sleep period each request.
It could be that the server is almost up, so you just want to try again in a second. But if that request fails, wait 2 seconds, but if that one fails, wait 4, etc.
It may be that you want to cap the amount of waiting to 30 seconds or a minute or something like that. It's probably wise to define the maximum number of tries so you don't just wait indefinitely.
Something like this might calculate your next delay in seconds:
seconds_to_wait = Math.min(60, Math.pow(2, try_num));
Your method will hammer the server with connection requests one after the other. You should include a Thread.sleep()
call in your catch
block (so it will only be executed if you actually need to wait) in order to wait a couple of seconds before you try again.
精彩评论