在 Java 中,使用 Socket 连接服务器并使用以下代码可能会产生java.net.ConnectException: Connection refused:
服务器关闭或尚未启动的错误。
try {
Socket clientSocket = new Socket(SERVER_IP, PORT);
} catch (IOException e) {
e.printStackTrace();
}
处理此异常的最佳方法是什么?您如何继续尝试连接,直到服务器可用而不会出现此问题?
更新:
我的方法是使用UDP,将消息发送到给定的端口,然后在给定的时间内等待响应,循环直到在启动套接字之前得到响应。
我正在寻找更好的方法。
沿着这些路线的东西怎么样:
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句