以下是一个简化版的WebSocket心跳机制实现的例子,仅包含核心代码:
后端(SpringBoot):
@Configuration
@EnableScheduling
public class WebSocketConfig {
@Autowired
private ServerEndpointExporter serverEndpointExporter;
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {
private static final ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();
private Session session;
private String userId;
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
sessionPool.put(userId, session);
System.out.println("新连接加入:" + userId);
}
@OnClose
public void onClose() {
sessionPool.remove(userId);
System.out.println("连接关闭:" + userId);
}
@OnMessage
public void onMessage(String message) {
// 处理消息
}
@Scheduled(fixedRate = 30000)
public void heartbeat() {
sessionPool.forEach((k, v) -> {
if (v.isOpen()) {
try {
v.getBasicRemote().sendText("心跳响应");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
前端(Vue.js):
<template>
<div>
<button @click="connect">连接WebSocket</button>
</div>
</template>
<script>
export default {
data() {
return {
ws: null,
heartbeatInterval: null
};
},
methods: {
connect() {
const userId = '用户ID';
const wsUrl = `ws://服务器地址/websocket/${userId}`;
this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => {
console.log('WebSocket连接成功');
this.heartbeatInterval = setInterval(() => {
this.ws.send('心跳请求');
}, 30000);
};
this.ws.onmessage = (message) => {
console.log('收到消息:', message.data);
// 处理消息
};
this.ws.onerror = (error) => {
console.error('WebSocket出错:', error);
};
this.ws.onclose = () => {
console.log('WebSocket连接关闭');
clearInterval(this.heartbeatInterval);
};
}
}
};
</script>
这个例子展示了如何在SpringBoot后端使用@EnableScheduling
和@Scheduled
注解来实现定时发送心跳消息,以及如何在Vue前端使用\`set