java socket长连接实现心跳检测代码
时间: 2023-11-27 17:03:13 浏览: 84
JAVA实现长连接(含心跳检测Demo)
下面是一个基于 Java Socket 的长连接实现心跳检测的代码示例:
客户端代码:
```java
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// 发送心跳包
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(() -> {
out.println("ping");
}, 0, 3, TimeUnit.SECONDS);
// 接收消息
String message;
while ((message = in.readLine()) != null) {
System.out.println(message);
}
}
}
```
服务端代码:
```java
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// 接收心跳包
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(() -> {
try {
String message = in.readLine();
if ("ping".equals(message)) {
out.println("pong");
}
} catch (IOException e) {
e.printStackTrace();
}
}, 0, 3, TimeUnit.SECONDS);
}
}
}
```
在客户端和服务端分别启动后,客户端会每隔 3 秒发送一个 "ping" 消息,服务端会每隔 3 秒接收客户端的消息并判断是否是心跳包,如果是则回复一个 "pong" 消息。这样就可以通过心跳检测来保持长连接的存活状态。
阅读全文