在Java中,要实现Socket连接断开后的自动重连,你可以使用以下方法:
以下是一个简单的示例代码:
import java.io.IOException;
import java.net.Socket;
public class AutoReconnectSocket {
private String host;
private int port;
private Socket socket;
private boolean isConnected;
public AutoReconnectSocket(String host, int port) {
this.host = host;
this.port = port;
this.isConnected = false;
}
public void connect() {
Thread reconnectThread = new Thread(() -> {
while (!isConnected) {
try {
socket = new Socket(host, port);
isConnected = true;
System.out.println("Connected to the server.");
} catch (IOException e) {
System.out.println("Connection failed, retrying in 5 seconds...");
try {
Thread.sleep(5000); // Wait for 5 seconds before retrying
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
});
reconnectThread.start();
}
public void disconnect() {
if (socket != null && !socket.isClosed()) {
try {
socket.close();
isConnected = false;
System.out.println("Disconnected from the server.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
AutoReconnectSocket autoReconnectSocket = new AutoReconnectSocket("localhost", 12345);
autoReconnectSocket.connect();
// Example: Disconnect after 10 seconds
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
autoReconnectSocket.disconnect();
}
}
这个示例中,我们创建了一个名为AutoReconnectSocket
的类,它包含了连接、断开连接和自动重连的逻辑。在connect()
方法中,我们创建了一个新的线程来处理重连逻辑。当连接断开时,线程会不断尝试重新连接,并在每次尝试之间等待5秒钟。当连接成功时,isConnected
变量将被设置为true
,表示连接已建立。在disconnect()
方法中,我们关闭Socket连接并将isConnected
设置为false
,以便重新尝试连接。