一、前言
springboot+vue快速搭建websocket简易模板。
二、后端
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.编写配置类
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter()
{
return new ServerEndpointExporter();
}
}
3.消息处理
- onopen:用于指定连接成功后执行
- onmessage:用于从服务器接收到信息时执行。
- onerror:用于指定连接失败后执行。
- onclose:用于指定连接关闭后执行。
@Component
@Slf4j
@ServerEndpoint("/websocket/message/{uid}")
public class WebSocketServer {
/**
* 存放所有在线的客户端
*/
private static Map<String, Session> onlineSessionClientMap = new ConcurrentHashMap<>();
/**
* 连接uid
*/
private String uid;
/**
* 连接会话
*/
private Session session;
/**
* 连接建立成功调用的方法。
*/
@OnOpen
public void onOpen(@PathParam("sid") String uid, Session session) {
onlineSessionClientMap.put(uid, session);
}
/**
* 连接关闭方法
*/
@OnClose
public void onClose(@PathParam("uid") String uid, Session session) {
onlineSessionClientMap.remove(uid);
}
/**
* 收到客户端消息后调用的方法。
*/
@OnMessage
public void onMessage(String message, Session session) {
onlineSessionClientMap.forEach((onlineSid, toSession)->{
toSession.getAsyncRemote().sendText(message);
});
}
/**
* 发生错误调用的方法
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
/**
* 群发消息
*/
private void sendToAll(String message) {
onlineSessionClientMap.forEach((onlineSid, toSession) -> {
if (!uid.equalsIgnoreCase(onlineSid)) {
toSession.getAsyncRemote().sendText(message);
}
});
}
/**
* 指定发送消息
*/
private void sendToOne(String toSid, String message) {
Session toSession = onlineSessionClientMap.get(toSid);
if (toSession == null) {
return;
}
toSession.getAsyncRemote().sendText(message);
}
}
三、前端
连接websocket,并加入心跳
let heartbeatTimer = null
const user = useUserStore()
const websocketState = reactive({
socket: null,
url: 'ws://127.0.0.1:8081/websocket/message/'+user.userId,
message: 'Hello, WebSocket!',
});
function connect () {
websocketState.socket = new WebSocket(websocketState.url);
websocketState.socket.onopen = () => {
console.log('WebSocket已连接');
startHeartbeat();
};
websocketState.socket.onclose = () => {
console.log('WebSocket已断开');
stopHeartbeat();
};
websocketState.socket.onmessage = (event) => {
console.log(`收到消息:${event.data}`);
if(event.data!='连接成功')
open2(event.data)
};
}
connect()
function startHeartbeat () {
// 每隔一定时间发送心跳消息
heartbeatTimer = setInterval(() => {
if (websocketState.socket.readyState === WebSocket.OPEN) {
websocketState.socket.send('Heartbeat')
} else {
console.log('WebSocket连接未打开')
connect()
}
}, 60000)
}
function stopHeartbeat () {
// 停止心跳定时器
clearInterval(heartbeatTimer)
}