在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”),以確認連接是否有效。如果一方在指定的時間內沒有收到心跳檢測消息,它會認為連接已經斷開,并采取相應的措施。