Java sockets: best way to retry upon Connection Refused exception?

ぃ、小莉子 提交于 2019-12-06 15:05:43

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));

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!