最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

websocket在springboot+vue中的使用教程

 更新時間:2019年08月17日 10:27:49   作者:會飛的joy  
這篇文章主要介紹了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調(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)長圖文生成的示例代碼

    Java如何實現(xiàn)長圖文生成的示例代碼

    這篇文章主要介紹了Java如何實現(xiàn)長圖文生成的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • idea 修改項目名和module名稱的操作

    idea 修改項目名和module名稱的操作

    這篇文章主要介紹了idea 修改項目名和module名稱的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Springboot項目快速實現(xiàn)攔截器功能

    Springboot項目快速實現(xiàn)攔截器功能

    上一篇文章介紹了Springboot項目如何快速實現(xiàn)過濾器功能,本篇文章接著來盤一盤攔截器,仔細研究后會發(fā)現(xiàn),其實攔截器和過濾器的功能非常類似,可以理解為面向切面編程的一種具體實現(xiàn)。感興趣的小伙伴可以參考閱讀
    2023-03-03
  • Java實現(xiàn)LeetCode(1.兩數(shù)之和)

    Java實現(xiàn)LeetCode(1.兩數(shù)之和)

    這篇文章主要介紹了Java實現(xiàn)LeetCode(兩數(shù)之和),本文使用java采用多種發(fā)放實現(xiàn)了LeetCode的兩數(shù)之和題目,需要的朋友可以參考下
    2021-06-06
  • AI算法實現(xiàn)五子棋(java)

    AI算法實現(xiàn)五子棋(java)

    這篇文章主要為大家詳細介紹了AI算法實現(xiàn)五子棋,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • SpringBoot自動配置深入探究實現(xiàn)原理

    SpringBoot自動配置深入探究實現(xiàn)原理

    在springboot的啟動類中可以看到@SpringBootApplication注解,它是SpringBoot的核心注解,也是一個組合注解。其中@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三個注解尤為重要。今天我們就來淺析這三個注解的含義
    2022-08-08
  • mybatis plus saveOrUpdate實現(xiàn)有重復(fù)數(shù)據(jù)就更新,否則新增方式

    mybatis plus saveOrUpdate實現(xiàn)有重復(fù)數(shù)據(jù)就更新,否則新增方式

    這篇文章主要介紹了mybatis plus saveOrUpdate實現(xiàn)有重復(fù)數(shù)據(jù)就更新,否則新增方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Java多線程案例之單例模式懶漢+餓漢+枚舉

    Java多線程案例之單例模式懶漢+餓漢+枚舉

    這篇文章主要介紹了Java多線程案例之單例模式懶漢+餓漢+枚舉,文章著重介紹在多線程的背景下簡單的實現(xiàn)單例模式,需要的小伙伴可以參考一下
    2022-06-06
  • 詳解JAVA設(shè)計模式之適配器模式

    詳解JAVA設(shè)計模式之適配器模式

    這篇文章主要介紹了JAVA設(shè)計模式之適配器模式的的相關(guān)資料,文中示例代碼非常詳細,供大家參考和學(xué)習(xí),感興趣的朋友可以了解
    2020-06-06

最新評論

青海省| 周至县| 合江县| 察雅县| 武功县| 吴堡县| 仪征市| 信丰县| 海淀区| 龙山县| 宜宾市| 栖霞市| 巴林左旗| 深水埗区| 土默特左旗| 达尔| 丰镇市| 榆林市| 万年县| 南部县| 呼伦贝尔市| 河北省| 深州市| 嘉荫县| 萨嘎县| 广南县| 怀宁县| 铅山县| 泾阳县| 电白县| 绵竹市| 新泰市| 赤壁市| 泰宁县| 比如县| 青河县| 重庆市| 九江县| 佛学| 金华市| 日照市|