websocket在springboot+vue中的使用教程
1、websocket在springboot中的一種實現(xiàn)
在java后臺中,websocket是作為一種服務(wù)端配置,其配置如下
@Configuration public class WebSocketConfig { @Bean(name="serverEndpointExporter") public ServerEndpointExporter getServerEndpointExporterBean(){ return new ServerEndpointExporter(); } }
加入上面的配置之后就可以編輯自己的websocket實現(xiàn)類了,如下
@Component @ServerEndpoint(value = "/messageSocket/{userId}") public class MessageWebSocket { private static final Logger logger = LoggerFactory.getLogger(MessageWebSocket.class); /** * 靜態(tài)變量,用來記錄當前在線連接數(shù)。應(yīng)該把它設(shè)計成線程安全的。 */ private static int onlineCount = 0; /** * key: userId value: sessionIds */ private static ConcurrentHashMap<Integer, ConcurrentLinkedQueue<String>> userSessionMap = new ConcurrentHashMap<>(); /** * concurrent包的線程安全Map,用來存放每個客戶端對應(yīng)的MyWebSocket對象。 */ private static ConcurrentHashMap<String, MessageWebSocket> websocketMap = new ConcurrentHashMap<>(); /** * key: sessionId value: userId */ private static ConcurrentHashMap<String, Integer> sessionUserMap = new ConcurrentHashMap<>(); /** * 當前連接會話,需要通過它來給客戶端發(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ā)送過來的消息 **/ @OnMessage public void onMessage(String messageStr, Session session, @PathParam("userId") Integer userId) throws IOException { } /** * * @param session * @param error 當連接發(fā)生錯誤時的回調(diào) */ @OnError public void onError(Session session, Throwable error) { String es = ExceptionUtils.getFullStackTrace(error); logger.error(es); } /** * 實現(xiàn)服務(wù)器主動推送 */ 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--; } }
到此后臺服務(wù)端的工作已經(jīng)做好了,前端如何作為客戶端進行連接呢,請繼續(xù)往下看。。
為了實現(xiàn)斷開自動重連,我們使用的reconnecting-websocket.js
組件
//websocket連接實例 let websocket = null; //初始話websocket實例 function initWebSocket(userId) { // ws地址 -->這里是你的請求路徑 let host = urlConfig.wsUrl + 'messageSocket/' + userId; if ('WebSocket' in window) { websocket = new ReconnectingWebSocket(host); // 連接錯誤 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)閉事件,當窗口關(guān)閉時,主動去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會拋異常。 window.onbeforeunload = function () { closeWebSocket(); } } else { alert('當前瀏覽器不支持websocket') return; } } //關(guān)閉WebSocket連接 function closeWebSocket() { websocket.close(); } //發(fā)送消息 function sendMessage(message){ websocket.send(message); }
至此一個簡易的完整的websocket已經(jīng)完成了,具體功能可以依此為基本進行擴展。
總結(jié)
以上所述是小編給大家介紹的websocket在springboot+vue中的使用教程,希望對大家有所幫助,如果大家有任何疑問歡迎給大家留言,小編會及時回復(fù)大家的!
相關(guān)文章
SpringMVC使用hibernate-validator進行參數(shù)校驗最佳實踐記錄
這篇文章主要介紹了SpringMVC使用hibernate-validator進行參數(shù)校驗最佳實踐,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05Spring Data Jpa 復(fù)合主鍵的實現(xiàn)
這篇文章主要介紹了Spring Data Jpa 復(fù)合主鍵的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04springboot整合RabbitMQ 中的 TTL實例代碼
TTL 是 RabbitMQ 中一個消息或者隊列的屬性,表明一條消息或者該隊列中的所有消息的最大存活時間,單位是毫秒,這篇文章主要介紹了springboot整合RabbitMQ 中的 TTL,需要的朋友可以參考下2022-09-09Mybatis-Plus的多數(shù)據(jù)源你了解嗎
這篇文章主要為大家詳細介紹了Mybatis-Plus的多數(shù)據(jù)源,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03spring中WebClient如何設(shè)置連接超時時間以及讀取超時時間
這篇文章主要給大家介紹了關(guān)于spring中WebClient如何設(shè)置連接超時時間以及讀取超時時間的相關(guān)資料,WebClient是Spring框架5.0引入的基于響應(yīng)式編程模型的HTTP客戶端,它提供一種簡便的方式來處理HTTP請求和響應(yīng),需要的朋友可以參考下2024-08-08spring boot項目如何采用war在tomcat容器中運行
這篇文章主要介紹了spring boot項目如何采用war在tomcat容器中運行呢,主要講述將SpringBoot打成war包并放入tomcat中運行的方法分享,需要的朋友可以參考下2022-11-11