在Java中,可以使用Socket连接进行心跳检测。心跳检测的主要目的是检测对方是否在线,通过定期发送小数据包来确认连接是否有效。以下是一个简单的心跳检测示例:
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class Server {
public static void main(String[] args) throws IOException, InterruptedException {
int port = 12345;
ExecutorService executorService = Executors.newFixedThreadPool(10);
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
executorService.submit(() -> handleClient(clientSocket));
}
}
private static void handleClient(Socket clientSocket) {
try {
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter writer = new PrintWriter(outputStream, true);
String heartBeatMessage = "HEARTBEAT";
ScheduledExecutorService heartbeatExecutor = Executors.newScheduledThreadPool(1);
heartbeatExecutor.scheduleAtFixedRate(() -> {
try {
writer.println(heartBeatMessage);
} catch (IOException e) {
System.out.println("Error sending heartbeat message: " + e.getMessage());
break;
}
}, 0, 30, TimeUnit.SECONDS); // 每30秒发送一次心跳检测
String inputLine;
while ((inputLine = reader.readLine()) != null) {
System.out.println("Received message from client: " + inputLine);
if (inputLine.equals("BYE")) {
break;
}
}
heartbeatExecutor.shutdown();
clientSocket.close();
} catch (IOException e) {
System.out.println("Error handling client: " + e.getMessage());
}
}
}
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
String serverAddress = "localhost";
int port = 12345;
Socket socket = new Socket(serverAddress, port);
System.out.println("Connected to server");
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter writer = new PrintWriter(outputStream, true);
String heartBeatMessage = "HEARTBEAT";
ScheduledExecutorService heartbeatExecutor = Executors.newScheduledThreadPool(1);
heartbeatExecutor.scheduleAtFixedRate(() -> {
try {
writer.println(heartBeatMessage);
} catch (IOException e) {
System.out.println("Error sending heartbeat message: " + e.getMessage());
break;
}
}, 0, 30, TimeUnit.SECONDS); // 每30秒发送一次心跳检测
String inputLine;
while ((inputLine = reader.readLine()) != null) {
System.out.println("Received message from server: " + inputLine);
if (inputLine.equals("BYE")) {
break;
}
}
heartbeatExecutor.shutdown();
socket.close();
}
}
在这个示例中,服务器和客户端都定期发送心跳检测消息(“HEARTBEAT”),以确认连接是否有效。如果一方在指定的时间内没有收到心跳检测消息,它会认为连接已经断开,并采取相应的措施。