Java的Socket通信完整实例(心跳包,客户端断线重连,服务端超时断开客户端连接)
时间: 2024-02-24 19:56:18 浏览: 108
好的,下面是一个Java的Socket通信完整实例,包括心跳包、客户端断线重连和服务端超时断开客户端连接的处理。
首先,我们需要定义一些常量和变量:
```java
private static final int SERVER_PORT = 8888; // 服务器端口
private static final String SERVER_HOST = "127.0.0.1"; // 服务器地址
private static final int HEARTBEAT_INTERVAL = 5000; // 心跳包间隔时间,单位:毫秒
private static final int RECONNECT_INTERVAL = 5000; // 断线重连间隔时间,单位:毫秒
private static final int TIMEOUT = 20000; // 超时时间,单位:毫秒
private Socket socket; // Socket对象
private BufferedReader reader; // 读取器
private PrintWriter writer; // 写入器
private Timer heartbeatTimer; // 心跳包定时器
private Timer reconnectTimer; // 断线重连定时器
private volatile boolean isConnecting = false; // 是否正在连接
private volatile boolean isConnected = false; // 是否已连接
```
然后,我们需要定义一些方法:
```java
/**
* 创建Socket连接
*/
private void createSocket() {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(SERVER_HOST, SERVER_PORT), TIMEOUT);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
isConnected = true;
startHeartbeat(); // 开始心跳包
} catch (IOException e) {
e.printStackTrace();
isConnected = false;
startReconnect(); // 开始断线重连
}
}
/**
* 发送数据
* @param data 数据
*/
private void sendData(String data) {
if (isConnected) {
writer.println(data);
writer.flush();
}
}
/**
* 接收数据
* @return 数据
*/
private String receiveData() {
String data = null;
if (isConnected) {
try {
data = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
isConnected = false;
startReconnect(); // 开始断线重连
}
}
return data;
}
/**
* 开始心跳包
*/
private void startHeartbeat() {
if (heartbeatTimer != null) {
heartbeatTimer.cancel();
}
heartbeatTimer = new Timer();
heartbeatTimer.schedule(new TimerTask() {
@Override
public void run() {
sendData("heartbeat"); // 发送心跳包
}
}, 0, HEARTBEAT_INTERVAL);
}
/**
* 开始断线重连
*/
private void startReconnect() {
if (!isConnecting && !isConnected) {
reconnectTimer = new Timer();
reconnectTimer.schedule(new TimerTask() {
@Override
public void run() {
if (!isConnected) {
isConnecting = true;
createSocket(); // 创建Socket连接
isConnecting = false;
} else {
reconnectTimer.cancel();
}
}
}, RECONNECT_INTERVAL);
}
}
/**
* 关闭Socket连接
*/
private void closeSocket() {
try {
if (socket != null) {
socket.close();
}
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
if (heartbeatTimer != null) {
heartbeatTimer.cancel();
}
if (reconnectTimer != null) {
reconnectTimer.cancel();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 监听连接状态
*/
private void listenConnectionState() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (isConnected) {
try {
socket.sendUrgentData(0xFF); // 发送紧急数据,测试连接状态
} catch (IOException e) {
e.printStackTrace();
isConnected = false;
startReconnect(); // 开始断线重连
}
}
}
}
}).start();
}
```
最后,我们编写一个测试方法:
```java
public static void main(String[] args) {
SocketClient client = new SocketClient();
client.createSocket(); // 创建Socket连接
client.listenConnectionState(); // 监听连接状态
while (true) {
String data = client.receiveData();
if (data != null) {
System.out.println("收到数据:" + data);
}
}
}
```
这样,我们就完成了一个Java的Socket通信完整实例,包括心跳包、客户端断线重连和服务端超时断开客户端连接的处理。
阅读全文