websocket在springboot+vue中的使用教程
1、websocket在springboot中的一種實(shí)現(xiàn)
在java后臺(tái)中,websocket是作為一種服務(wù)端配置,其配置如下
@Configuration
public class WebSocketConfig {
@Bean(name="serverEndpointExporter")
public ServerEndpointExporter getServerEndpointExporterBean(){
return new ServerEndpointExporter();
}
}
加入上面的配置之后就可以編輯自己的websocket實(shí)現(xiàn)類了,如下
@Component
@ServerEndpoint(value = "/messageSocket/{userId}")
public class MessageWebSocket {
private static final Logger logger = LoggerFactory.getLogger(MessageWebSocket.class);
/**
* 靜態(tài)變量,用來(lái)記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。
*/
private static int onlineCount = 0;
/**
* key: userId value: sessionIds
*/
private static ConcurrentHashMap<Integer, ConcurrentLinkedQueue<String>> userSessionMap = new ConcurrentHashMap<>();
/**
* concurrent包的線程安全Map,用來(lái)存放每個(gè)客戶端對(duì)應(yīng)的MyWebSocket對(duì)象。
*/
private static ConcurrentHashMap<String, MessageWebSocket> websocketMap = new ConcurrentHashMap<>();
/**
* key: sessionId value: userId
*/
private static ConcurrentHashMap<String, Integer> sessionUserMap = new ConcurrentHashMap<>();
/**
* 當(dāng)前連接會(huì)話,需要通過它來(lái)給客戶端發(fā)送數(shù)據(jù)
*/
private Session session;
/**
* 連接建立成功調(diào)用的方法
* */
@OnOpen
public void onOpen(Session session, @PathParam("userId") Integer userId) {
System.out.println(applicationContext);
try {
this.session = session;
String sessionId = session.getId();
//建立userId和sessionId的關(guān)系
if(userSessionMap.containsKey(userId)) {
userSessionMap.get(userId).add(sessionId);
}else{
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
queue.add(sessionId);
userSessionMap.put(userId, queue);
}
sessionUserMap.put(sessionId, userId);
//建立sessionId和websocket引用的關(guān)系
if(!websocketMap.containsKey(sessionId)){
websocketMap.put(sessionId, this);
addOnlineCount(); //在線數(shù)加1
}
}catch (Exception e){
logger.error("連接失敗");
String es = ExceptionUtils.getFullStackTrace(e);
logger.error(es);
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
String sessionId = this.session.getId();
//移除userId和sessionId的關(guān)系
Integer userId = sessionUserMap.get(sessionId);
sessionUserMap.remove(sessionId);
if(userId != null) {
ConcurrentLinkedQueue<String> sessionIds = userSessionMap.get(userId);
if(sessionIds != null) {
sessionIds.remove(sessionId);
if (sessionIds.size() == 0) {
userSessionMap.remove(userId);
}
}
}
//移除sessionId和websocket的關(guān)系
if (websocketMap.containsKey(sessionId)) {
websocketMap.remove(sessionId);
subOnlineCount(); //在線數(shù)減1
}
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param messageStr 客戶端發(fā)送過來(lái)的消息
**/
@OnMessage
public void onMessage(String messageStr, Session session, @PathParam("userId") Integer userId) throws IOException {
}
/**
*
* @param session
* @param error 當(dāng)連接發(fā)生錯(cuò)誤時(shí)的回調(diào)
*/
@OnError
public void onError(Session session, Throwable error) {
String es = ExceptionUtils.getFullStackTrace(error);
logger.error(es);
}
/**
* 實(shí)現(xiàn)服務(wù)器主動(dòng)推送
*/
public void sendMessage(String message, Integer toUserId) throws IOException {
if(toUserId != null && !StringUtil.isEmpty(message.trim())){
ConcurrentLinkedQueue<String> sessionIds = userSessionMap.get(toUserId);
if(sessionIds != null) {
for (String sessionId : sessionIds) {
MessageWebSocket socket = websocketMap.get(sessionId);
socket.session.getBasicRemote().sendText(message);
}
}
}else{
logger.error("未找到接收用戶連接,該用戶未連接或已斷開");
}
}
public void sendMessage(String message, Session session) throws IOException {
session.getBasicRemote().sendText(message);
}
/**
*獲取在線人數(shù)
*/
public static synchronized int getOnlineCount() {
return onlineCount;
}
/**
*在線人數(shù)加一
*/
public static synchronized void addOnlineCount() {
MessageWebSocket.onlineCount++;
}
/**
*在線人數(shù)減一
*/
public static synchronized void subOnlineCount() {
MessageWebSocket.onlineCount--;
}
}
到此后臺(tái)服務(wù)端的工作已經(jīng)做好了,前端如何作為客戶端進(jìn)行連接呢,請(qǐng)繼續(xù)往下看。。
為了實(shí)現(xiàn)斷開自動(dòng)重連,我們使用的reconnecting-websocket.js組件
//websocket連接實(shí)例
let websocket = null;
//初始話websocket實(shí)例
function initWebSocket(userId) {
// ws地址 -->這里是你的請(qǐng)求路徑
let host = urlConfig.wsUrl + 'messageSocket/' + userId;
if ('WebSocket' in window) {
websocket = new ReconnectingWebSocket(host);
// 連接錯(cuò)誤
websocket.onerror = function () {
}
// 連接成功
websocket.onopen = function () {
}
// 收到消息的回調(diào),e.data為收到的信息
websocket.onmessage = function (e) {
}
// 連接關(guān)閉的回調(diào)
websocket.onclose = function () {
}
//監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會(huì)拋異常。
window.onbeforeunload = function () {
closeWebSocket();
}
} else {
alert('當(dāng)前瀏覽器不支持websocket')
return;
}
}
//關(guān)閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
//發(fā)送消息
function sendMessage(message){
websocket.send(message);
}
至此一個(gè)簡(jiǎn)易的完整的websocket已經(jīng)完成了,具體功能可以依此為基本進(jìn)行擴(kuò)展。
總結(jié)
以上所述是小編給大家介紹的websocket在springboot+vue中的使用教程,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給大家留言,小編會(huì)及時(shí)回復(fù)大家的!
相關(guān)文章
Java調(diào)用構(gòu)造函數(shù)和方法及使用詳解
在Java編程中,構(gòu)造函數(shù)用于初始化新創(chuàng)建的對(duì)象,而方法則用于執(zhí)行對(duì)象的行為,構(gòu)造函數(shù)在使用new關(guān)鍵字創(chuàng)建類實(shí)例時(shí)自動(dòng)調(diào)用,沒有返回類型,并且名稱與類名相同,本文通過示例詳細(xì)介紹了如何在Java中使用構(gòu)造函數(shù)和方法,感興趣的朋友一起看看吧2024-10-10
Java如何實(shí)現(xiàn)長(zhǎng)圖文生成的示例代碼
這篇文章主要介紹了Java如何實(shí)現(xiàn)長(zhǎng)圖文生成的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2017-08-08
Springboot項(xiàng)目快速實(shí)現(xiàn)攔截器功能
上一篇文章介紹了Springboot項(xiàng)目如何快速實(shí)現(xiàn)過濾器功能,本篇文章接著來(lái)盤一盤攔截器,仔細(xì)研究后會(huì)發(fā)現(xiàn),其實(shí)攔截器和過濾器的功能非常類似,可以理解為面向切面編程的一種具體實(shí)現(xiàn)。感興趣的小伙伴可以參考閱讀2023-03-03
Java實(shí)現(xiàn)LeetCode(1.兩數(shù)之和)
這篇文章主要介紹了Java實(shí)現(xiàn)LeetCode(兩數(shù)之和),本文使用java采用多種發(fā)放實(shí)現(xiàn)了LeetCode的兩數(shù)之和題目,需要的朋友可以參考下2021-06-06
SpringBoot自動(dòng)配置深入探究實(shí)現(xiàn)原理
在springboot的啟動(dòng)類中可以看到@SpringBootApplication注解,它是SpringBoot的核心注解,也是一個(gè)組合注解。其中@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三個(gè)注解尤為重要。今天我們就來(lái)淺析這三個(gè)注解的含義2022-08-08
mybatis plus saveOrUpdate實(shí)現(xiàn)有重復(fù)數(shù)據(jù)就更新,否則新增方式
這篇文章主要介紹了mybatis plus saveOrUpdate實(shí)現(xiàn)有重復(fù)數(shù)據(jù)就更新,否則新增方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12

