问题描述
现在我正在这样做:
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)
将生成 ConnectionRefused
异常。我在一个单独的线程中运行我的代码,所以我不担心阻塞。鉴于此,我的重试方法是否适当或有更好的方法???
downloadSock.connect(sockaddr)
will generate a ConnectionRefused
exception 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???
谢谢!
推荐答案
在这种情况下,我通常会在每次请求时使用逐渐延长的睡眠时间。
In this case I usually use a progressively longer sleep period each request.
可能是服务器差不多了,所以你只想在一秒钟后再试一次。但如果该请求失败,请等待2秒,但如果该请求失败,请等待4等等。
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.
可能是您要等待等待的数量为30几秒钟或一分钟或类似的事情。定义最大尝试次数可能是明智的,因此您不必无限期地等待。
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));
这篇关于Java套接字:重试Connection Refused异常的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!