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)文章
Java調(diào)用構(gòu)造函數(shù)和方法及使用詳解
在Java編程中,構(gòu)造函數(shù)用于初始化新創(chuàng)建的對象,而方法則用于執(zhí)行對象的行為,構(gòu)造函數(shù)在使用new關(guān)鍵字創(chuàng)建類實例時自動調(diào)用,沒有返回類型,并且名稱與類名相同,本文通過示例詳細介紹了如何在Java中使用構(gòu)造函數(shù)和方法,感興趣的朋友一起看看吧2024-10-10
Java實現(xiàn)LeetCode(1.兩數(shù)之和)
這篇文章主要介紹了Java實現(xiàn)LeetCode(兩數(shù)之和),本文使用java采用多種發(fā)放實現(xiàn)了LeetCode的兩數(shù)之和題目,需要的朋友可以參考下2021-06-06
mybatis plus saveOrUpdate實現(xiàn)有重復(fù)數(shù)據(jù)就更新,否則新增方式
這篇文章主要介紹了mybatis plus saveOrUpdate實現(xiàn)有重復(fù)數(shù)據(jù)就更新,否則新增方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12

