TCP 客户端断线重连java代码
时间: 2024-09-12 18:09:21 浏览: 37
TCP客户端断线重连通常会涉及到网络IO操作和异常处理。下面是一个简单的Java示例,展示了如何使用`Socket`和`ServerSocket`以及`BufferedReader`和`PrintWriter`进行TCP连接,并包含了一个重连机制:
```java
import java.io.*;
import java.net.*;
public class TcpClient {
private static final int RETRY_INTERVAL = 5000; // 重试间隔,单位毫秒
private String host;
private int port;
public TcpClient(String host, int port) {
this.host = host;
this.port = port;
}
public void reconnect() throws IOException {
while (true) {
try (Socket socket = new Socket(host, port);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)) {
// 连接成功后的操作
System.out.println("Connected to server at " + host + ":" + port);
String inputLine;
while ((inputLine = reader.readLine()) != null) {
System.out.println("Received from server: " + inputLine);
}
// 发送请求等...
writer.println("Hello, Server!");
} catch (IOException e) {
if (!isConnectionFailed(e)) {
throw e;
}
System.out.println("Connection failed, retrying in " + RETRY_INTERVAL / 1000 + " seconds...");
Thread.sleep(RETRY_INTERVAL);
}
}
}
private boolean isConnectionFailed(IOException e) {
// 检查是否是因为连接失败而非其他原因(如读取错误)
return e instanceof ConnectException || e.getMessage().contains("Connection refused") ||
e.getMessage().contains("Connection timed out");
}
public static void main(String[] args) {
TcpClient client = new TcpClient("localhost", 8080); // 替换为你需要连接的实际服务器地址和端口
try {
client.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文