java socket客户端长连接 实现断线重连的代码
时间: 2023-07-30 13:06:28 浏览: 181
java socket长连接客户端服务端(标准实例)
以下是 Java Socket 客户端实现断线重连的代码示例:
```java
public class SocketClient {
private String host;
private int port;
private Socket socket;
private boolean isConnected = false;
private int maxReconnectTimes = 5;
private int currentReconnectTimes = 0;
public SocketClient(String host, int port) {
this.host = host;
this.port = port;
}
public void connect() {
while (true) {
try {
socket = new Socket(host, port);
isConnected = true;
currentReconnectTimes = 0;
// 连接成功后进行通信
communicate();
} catch (IOException e) {
isConnected = false;
currentReconnectTimes++;
if (currentReconnectTimes > maxReconnectTimes) {
// 达到最大重连次数后退出重连
System.out.println("重连次数已达到最大值,退出重连");
break;
}
try {
// 重连间隔为1秒,可以根据实际情况进行调整
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("连接失败,正在进行第" + currentReconnectTimes + "次重连...");
}
}
}
private void communicate() throws IOException {
// 连接成功后进行通信
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (isConnected) {
// 发送数据
out.println("Hello, server!");
// 接收数据
String line = in.readLine();
System.out.println("Received from server: " + line);
// 模拟长连接
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
在主程序中,可以创建 SocketClient 对象并进行连接:
```java
public class Main {
public static void main(String[] args) {
SocketClient client = new SocketClient("127.0.0.1", 8000);
client.connect();
}
}
```
在 SocketClient 中,使用了 while 循环进行断线重连,并且在重连失败后使用 Thread.sleep() 方法等待一段时间再进行重连,避免频繁重连导致服务器受到过多的连接请求。在每次连接成功后,使用 communicate() 方法进行通信,并在通信过程中模拟长连接。
阅读全文