在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
,以便重新嘗試連接。