在Java中,可以使用Socket來實現心跳機制,通過在客戶端和服務器端發送和接收心跳包來保持連接的活躍性。以下是一個簡單的示例代碼來實現心跳機制:
客戶端代碼:
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
String serverAddress = "127.0.0.1";
int serverPort = 8888;
try {
Socket socket = new Socket(serverAddress, serverPort);
OutputStream outputStream = socket.getOutputStream();
while (true) {
// 發送心跳包
String heartbeatMsg = "heartbeat";
outputStream.write(heartbeatMsg.getBytes());
outputStream.flush();
Thread.sleep(5000); // 每隔5秒發送一次心跳包
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
服務器端代碼:
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
int serverPort = 8888;
try {
ServerSocket serverSocket = new ServerSocket(serverPort);
System.out.println("Server started...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected: " + socket.getInetAddress());
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
String msg = new String(buffer, 0, len);
System.out.println("Received message: " + msg);
// 判斷是否為心跳包
if (msg.equals("heartbeat")) {
System.out.println("Received heartbeat from client");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的示例代碼中,客戶端在循環中每隔5秒發送一次心跳包給服務器,服務器接收到心跳包后進行判斷并輸出相關信息。通過這種方式可以實現簡單的心跳機制來保持連接的活躍性。