Java socket长连接心跳检测代码
时间: 2023-09-11 12:10:40 浏览: 72
Socket长连接心跳
以下是一个简单的Java socket长连接心跳检测代码示例:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class HeartbeatClient {
private static final int SERVER_PORT = 8888;
private static final String SERVER_IP = "127.0.0.1";
private static final long HEARTBEAT_INTERVAL = 5000; // 心跳间隔时间,单位毫秒
public static void main(String[] args) {
Socket socket = null;
InputStream in = null;
OutputStream out = null;
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
in = socket.getInputStream();
out = socket.getOutputStream();
// 发送心跳包
new Thread(new HeartbeatThread(out)).start();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
String message = new String(buffer, 0, len);
System.out.println("收到服务器的消息:" + message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class HeartbeatThread implements Runnable {
private OutputStream out;
public HeartbeatThread(OutputStream out) {
this.out = out;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(HEARTBEAT_INTERVAL);
out.write("heartbeat".getBytes());
out.flush();
System.out.println("发送心跳包");
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}
}
}
```
这个示例中,我们在客户端和服务器之间建立了一个长连接,并且每隔一段时间就发送一个心跳包到服务器,以确保连接不会因为长时间没有数据交换而断开。在线程中,我们使用了`Thread.sleep()`来实现心跳包发送的定时器功能。当连接断开或者发送心跳包失败时,我们可以在`catch`块中重新连接或者做其他处理。
阅读全文