Springboot+Vue+Websocket 事例
Springboot
1.Maven導(dǎo)入websocket依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.加入websocket配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author :宗
* @date :Created in 2023/10/13 10:31
* @description:WebSocket配置類
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
System.out.println("config");
return new ServerEndpointExporter();
}
}
3.封裝websocket常用方法
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author :宗
* @date :Created in 2023/10/13 10:35
* @description:
*/
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {
/**
* 靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計成線程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的線程安全Set,用來存放每個客戶端對應(yīng)的MyWebSocket對象。
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**
* 與某個客戶端的連接會話,需要通過它來給客戶端發(fā)送數(shù)據(jù)
*/
private Session session;
/**
* 接收userId
*/
private String userId = "";
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
System.out.println("-------------------> onOpen");
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
//加入set中
} else {
webSocketMap.put(userId, this);
//加入set中
addOnlineCount();
//在線數(shù)加1
}
log.info("用戶連接:" + userId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount());
try {
HashMap<Object, Object> map = new HashMap<>();
map.put("key", "連接成功");
sendMessage(JSON.toJSONString(map));
} catch (IOException e) {
log.error("用戶:" + userId + ",網(wǎng)絡(luò)異常!!!!!!");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
System.out.println("-------------------> onClose");
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
//從set中刪除
subOnlineCount();
}
log.info("用戶退出:" + userId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過來的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("-------------------> onMessage");
log.info("用戶消息:" + userId + ",報文:" + message);
//可以群發(fā)消息
//消息保存到數(shù)據(jù)庫、redis
if (StringUtils.isNotBlank(message)) {
try {
//解析發(fā)送的報文
JSONObject jsonObject = JSONObject.parseObject(message);
//追加發(fā)送人(防止串改)
jsonObject.put("fromUserId", this.userId);
String fromUserId = jsonObject.getString("fromUserId");
//傳送給對應(yīng)toUserId用戶的websocket
if (StringUtils.isNotBlank(fromUserId) && webSocketMap.containsKey(fromUserId)) {
webSocketMap.get(fromUserId).sendMessage(jsonObject.toJSONString());
//自定義-業(yè)務(wù)處理
// DeviceLocalThread.paramData.put(jsonObject.getString("group"),jsonObject.toJSONString());
} else {
log.error("請求的userId:" + fromUserId + "不在該服務(wù)器上");
//否則不在這個服務(wù)器上,發(fā)送到mysql或者redis
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 發(fā)生錯誤時候
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("-------------------> onError");
log.error("用戶錯誤:" + this.userId + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 實現(xiàn)服務(wù)器主動推送
*/
public void sendMessage(String message) throws IOException {
System.out.println("-------------------> sendMessage");
//加入線程鎖
synchronized (session) {
try {
//同步發(fā)送信息
this.session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("服務(wù)器推送失敗:" + e.getMessage());
}
}
}
/**
* 發(fā)送自定義消息
* */
/**
* 發(fā)送自定義消息
*
* @param message 發(fā)送的信息
* @param toUserId 如果為null默認(rèn)發(fā)送所有
* @throws IOException
*/
public static void sendInfo(String message, String toUserId) throws IOException {
System.out.println("-------------------> sendInfo");
//如果userId為空,向所有群體發(fā)送
if (StringUtils.isEmpty(toUserId)) {
//向所有用戶發(fā)送信息
Iterator<String> itera = webSocketMap.keySet().iterator();
while (itera.hasNext()) {
String keys = itera.next();
WebSocketServer item = webSocketMap.get(keys);
item.sendMessage(message);
}
}
//如果不為空,則發(fā)送指定用戶信息
else if (webSocketMap.containsKey(toUserId)) {
WebSocketServer item = webSocketMap.get(toUserId);
item.sendMessage(message);
} else {
log.error("請求的userId:" + toUserId + "不在該服務(wù)器上");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
public static synchronized ConcurrentHashMap<String, WebSocketServer> getWebSocketMap() {
return WebSocketServer.webSocketMap;
}
}
4.1使用postman進(jìn)行ws的測試
4.2使用網(wǎng)頁進(jìn)行ws測試(支持localhost本地測試)
網(wǎng)站地址:http://www.websocket-test.com/
Vue前端配置
在App.vue中添加如下代碼,針對于使用框架的,直接復(fù)制就好了。
<script>
export default {
data() {
return {
// socket參數(shù)
socket: null,
timeout: 10 * 1000, // 45秒一次心跳
timeoutObj: null, // 心跳心跳倒計時
serverTimeoutObj: null, // 心跳倒計時
timeoutnum: null, // 斷開 重連倒計時
lockReconnect: false, // 防止
websocket: null
};
},
methods: {
initWebSocket() {
// WebSocket與普通的請求所用協(xié)議有所不同,ws等同于http,wss等同于https
let wsUrl = 'ws://localhost:9898/api/v1/websocket/' + localStorage.getItem('ms_username');
this.websocket = new WebSocket(wsUrl);
this.websocket.onopen = this.websocketonopen;
this.websocket.onerror = this.websocketonerror;
this.websocket.onmessage = this.setOnmessageMessage;
this.websocket.onclose = this.websocketclose;
// 監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時,主動去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會拋異常。
// window.onbeforeunload = that.onbeforeunload
},
start() {
console.log('start');
console.log(localStorage.getItem('ms_username'));
//清除延時器
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(() => {
if (this.websocket && this.websocket.readyState == 1) {
// let actions = { 'test': '12345' };
// this.websocket.send(JSON.stringify(actions));//發(fā)送消息,服務(wù)端返回信息,即表示連接良好,可以在socket的onmessage事件重置心跳機制函數(shù)
} else {
this.reconnect();
}
//定義一個延時器等待服務(wù)器響應(yīng),若超時,則關(guān)閉連接,重新請求server建立socket連接
this.serverTimeoutObj = setTimeout(() => {
this.websocket.close();
}, this.timeout);
}, this.timeout);
},
reset() { // 重置心跳
// 清除時間
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
// 重啟心跳
this.start();
},
// 重新連接
reconnect() {
if (this.lockReconnect) return;
this.lockReconnect = true;
//沒連接上會一直重連,設(shè)置延遲避免請求過多
this.timeoutnum && clearTimeout(this.timeoutnum);
this.timeoutnum = setTimeout(() => {
this.initWebSocket();
this.lockReconnect = false;
}, 5000);
},
async setOnmessageMessage(event) {
// console.log(event.data, '獲得消息');
this.reset();
// 自定義全局監(jiān)聽事件
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: event.data
}
}));
//發(fā)現(xiàn)消息進(jìn)入 開始處理前端觸發(fā)邏輯
// if (event.data === 'success' || event.data === 'heartBath') return
},
websocketonopen() {
//開啟心跳
this.start();
console.log('WebSocket連接成功!!!' + new Date() + '----' + this.websocket.readyState);
clearInterval(this.otimer);//停止
},
websocketonerror(e) {
console.log('WebSocket連接發(fā)生錯誤' + e);
},
websocketclose(e) {
this.websocket.close();
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
console.log('WebSocket連接關(guān)閉');
},
websocketsend(messsage) {
that.websocket.send(messsage);
},
closeWebSocket() { // 關(guān)閉websocket
that.websocket.close();
}
// // 收到消息處理
// getSocketData (res) {
// if (res.detail.data === 'success' || res.detail.data === 'heartBath') return
// // ...業(yè)務(wù)處理
// }
},
mounted() {
this.initWebSocket();
}
};
</script>
在需要使用的界面添加監(jiān)聽器
methods:{
getSocketData(res) {
let parse = JSON.parse(res.detail.data);
console.log(parse.msg);
}
},
mounted() {
window.addEventListener('onmessageWS', this.getSocketData);
}
到此不出意外的話,【應(yīng)該出意外了(bushi)】,就配置好了!