欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

websocket在springboot+vue中的使用教程

 更新時(shí)間:2019年08月17日 10:27:49   作者:會(huì)飛的joy  
這篇文章主要介紹了websocket在springboot+vue中的使用教程,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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ì)話,需要通過(guò)它來(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ā)送過(guò)來(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("未找到接收用戶連接,該用戶未連接或已斷開(kāi)");
    }
  }
  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)斷開(kāi)自動(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)聽(tīng)窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒(méi)斷開(kāi)就關(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ì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給大家留言,小編會(huì)及時(shí)回復(fù)大家的!

相關(guān)文章

  • SpringBoot讀寫操作yml配置文件方法

    SpringBoot讀寫操作yml配置文件方法

    之前一直用的application.properties配置文件,只能是KV結(jié)構(gòu),后來(lái)的yml配置文件更像是樹(shù)狀結(jié)構(gòu),支持層級(jí),比properties更靈活
    2023-01-01
  • SpringMVC使用hibernate-validator進(jìn)行參數(shù)校驗(yàn)最佳實(shí)踐記錄

    SpringMVC使用hibernate-validator進(jìn)行參數(shù)校驗(yàn)最佳實(shí)踐記錄

    這篇文章主要介紹了SpringMVC使用hibernate-validator進(jìn)行參數(shù)校驗(yàn)最佳實(shí)踐,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-05-05
  • SpringBoot緩存Ehcache的使用詳解

    SpringBoot緩存Ehcache的使用詳解

    EhCache、Redis比較常用,使用Redis的時(shí)候需要先安裝Redis服務(wù)器,本文給大家介紹SpringBoot緩存Ehcache的使用詳解,感興趣的朋友跟隨小編一起看看吧
    2022-03-03
  • Spring Data Jpa 復(fù)合主鍵的實(shí)現(xiàn)

    Spring Data Jpa 復(fù)合主鍵的實(shí)現(xiàn)

    這篇文章主要介紹了Spring Data Jpa 復(fù)合主鍵的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • springboot整合RabbitMQ 中的 TTL實(shí)例代碼

    springboot整合RabbitMQ 中的 TTL實(shí)例代碼

    TTL 是 RabbitMQ 中一個(gè)消息或者隊(duì)列的屬性,表明一條消息或者該隊(duì)列中的所有消息的最大存活時(shí)間,單位是毫秒,這篇文章主要介紹了springboot整合RabbitMQ 中的 TTL,需要的朋友可以參考下
    2022-09-09
  • Redis作為緩存應(yīng)用的情形詳細(xì)分析

    Redis作為緩存應(yīng)用的情形詳細(xì)分析

    實(shí)際開(kāi)發(fā)中緩存處理是必須的,不可能我們每次客戶端去請(qǐng)求一次服務(wù)器,服務(wù)器每次都要去數(shù)據(jù)庫(kù)中進(jìn)行查找,為什么要使用緩存?說(shuō)到底是為了提高系統(tǒng)的運(yùn)行速度
    2023-01-01
  • Mybatis-Plus的多數(shù)據(jù)源你了解嗎

    Mybatis-Plus的多數(shù)據(jù)源你了解嗎

    這篇文章主要為大家詳細(xì)介紹了Mybatis-Plus的多數(shù)據(jù)源,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2022-03-03
  • spring中WebClient如何設(shè)置連接超時(shí)時(shí)間以及讀取超時(shí)時(shí)間

    spring中WebClient如何設(shè)置連接超時(shí)時(shí)間以及讀取超時(shí)時(shí)間

    這篇文章主要給大家介紹了關(guān)于spring中WebClient如何設(shè)置連接超時(shí)時(shí)間以及讀取超時(shí)時(shí)間的相關(guān)資料,WebClient是Spring框架5.0引入的基于響應(yīng)式編程模型的HTTP客戶端,它提供一種簡(jiǎn)便的方式來(lái)處理HTTP請(qǐng)求和響應(yīng),需要的朋友可以參考下
    2024-08-08
  • java反編譯工具jd-gui使用詳解

    java反編譯工具jd-gui使用詳解

    JD-GUI是一個(gè)獨(dú)立的圖形實(shí)用程序,顯示“.class”文件的Java源代碼,本文主要介紹了java反編譯工具jd-gui使用詳解,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-09-09
  • spring boot項(xiàng)目如何采用war在tomcat容器中運(yùn)行

    spring boot項(xiàng)目如何采用war在tomcat容器中運(yùn)行

    這篇文章主要介紹了spring boot項(xiàng)目如何采用war在tomcat容器中運(yùn)行呢,主要講述將SpringBoot打成war包并放入tomcat中運(yùn)行的方法分享,需要的朋友可以參考下
    2022-11-11

最新評(píng)論