在Java中,使用Socket连接到具有以下代码的服务器可能会在服务器关闭或尚未启动时生成java.net.ConnectException: Connection refused:
错误。
try {
Socket clientSocket = new Socket(SERVER_IP, PORT);
} catch (IOException e) {
e.printStackTrace();
}
处理此异常的最佳方法是什么?如何在没有此问题的情况下继续尝试连接,直到服务器可用?
更新
我的方法是使用UDP,将消息发送到给定端口,然后在给定时间内等待响应,循环直到我在启动套接字之前得到响应。
我正在寻找更好的方法。
答案 0 :(得分:0)
这些方面的内容如何:
String SERVER_IP = "ip";
int PORT = 0;
int maxTries = 10;
int timeBeforeRetry = 5000; //ms
int count = 0;
Socket clientSocket = null;
while(clientSocket == null && count < maxTries) {
try {
clientSocket = new Socket(SERVER_IP, PORT);
} catch(IOException e) {
// Log if you want
try {
Thread.sleep(timeBeforeRetry);
} catch(InterruptedException e) { /* can be ignored or logged I guess */ }
}
count++;
}
if(clientSocket == null) {
// throw some kind of exception
}