我将为您提供这种处理程序,我在我的小游戏中使用它。
几次尝试后,它也会放弃。
private static int MAX_CONNECTION = 10;
private int reconnections = 0;
public void connect() {
try {
this.socket = new Socket();
InetSocketAddress sa = new InetSocketAddress(this.server, this.port);
this.socket.connect(sa,500);
this.connected = true;
this.in = new InputStreamReader(this.socket.getInputStream());
this.out = new OutputStreamWriter(this.socket.getOutputStream());
} catch (ConnectException e) {
System.out.println("Error while connecting. " + e.getMessage());
this.tryToReconnect();
} catch (SocketTimeoutException e) {
System.out.println("Connection: " + e.getMessage() + ".");
this.tryToReconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
private void tryToReconnect() {
this.disconnect();
System.out.println("I will try to reconnect in 10 seconds... (" + this.reconnections + "/10)");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
if (this.reconnections < MAX_RECONNECTIONS) {
this.reconnections++;
this.connect();
} else {
System.out.println("Reconnection failed, exeeded max reconnection tries. Shutting down.");
this.disconnect();
System.exit(0);
return;
}
}
以下是代码的解释:
private static final int MAX_CONNECTION = 10
private int reconnections = 0
首先,我声明了两个变量,其中一个是固定的,在运行时不能更改,它是我希望客户端在关闭之前尝试的最大次数。第二个变量是当前重新连接的尝试次数。
公共方法connect()用于连接套接字。我将跳过异常处理:
} catch (ConnectException e) {
System.out.println("Error while connecting. " + e.getMessage());
this.tryToReconnect();
} catch (SocketTimeoutException e) {
System.out.println("Connection: " + e.getMessage() + ".");
this.tryToReconnect();
}
当连接异常抛出时,捕获器会调用重新连接方法。
重新连接方法在每次尝试之间等待10秒,并且如果连接失败,则由connect()每次调用此方法。
如果连接已建立,则connect()不会再次调用tryToReconnect()。
如果在100秒内(即10次尝试,每10秒一次)无法连接,则程序退出。