在Java中,我們可以使用Spring Boot框架和Spring WebSocket庫來實現WebSocket服務器。為了處理心跳包,我們可以在客戶端和服務器端都實現心跳檢測的邏輯。這里是一個簡單的示例:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
}
@Controller
public class WebSocketController {
@MessageMapping("/sendHeartbeat")
@SendTo("/topic/heartbeat")
public String sendHeartbeat() {
return "Heartbeat sent";
}
}
function sendHeartbeat() {
if (socket.readyState === WebSocket.OPEN) {
socket.send('{"type": "heartbeat"}');
}
}
setInterval(sendHeartbeat, 30000); // 每30秒發送一次心跳包
@MessageMapping("/app/heartbeat")
public void handleHeartbeat(@Payload HeartbeatMessage message, SimpMessageHeaderAccessor headerAccessor) {
headerAccessor.getSessionAttributes().put("lastHeartbeat", System.currentTimeMillis());
}
在這個示例中,我們創建了一個簡單的WebSocket服務器,客戶端定期發送心跳包,服務器端處理這些心跳包并更新客戶端的最后心跳時間。你可以根據實際需求對這個示例進行擴展和優化。