springcloud + vue + websocket


1.前端

前端監聽地址:ip:webSocket服務的端口號/webSocket/參數

mounted() {// 初始化WebSocket
    this.initWebSocket();
},
methods: {
  //======================= WebSocket相關 =======================
    initWebSocket: function() {
      if (typeof WebSocket === "undefined") {
        alert("您的瀏覽器不支持socket");
      } else {
        // 監聽地址
        this.notifyUrl = this.notifyUrl + "webSocket/" + this.sysUser.userId;
        // 實例化socket
        this.socket = new WebSocket(this.notifyUrl);
        // 監聽socket連接
        this.socket.onopen = this.openWebSocket;
        // 監聽socket錯誤信息
        this.socket.onerror = this.errorWebSocket;
        // 監聽socket消息
        this.socket.onmessage = this.getSocketMsg;
     // 路由跳轉時結束websocket鏈接
        let testSocket = this.socket;
        this.$router.afterEach(function() {
          testSocket.close();
        });
      }
    },
    openWebSocket: function() {
      console.log("WebSocket連接成功");
    },
    errorWebSocket: function() {
      console.log("WebSocket連接發生錯誤");
    },
    // 監聽后端獲取數據
    getSocketMsg: function(msg) {
      this.payResult = msg.data;
    },
    closeWebSocket: function() {
      console.log("socket已經關閉");
    }
}
 

 

2.WebSocket所在服務Pom文件

<!--websocket-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

 

3.WebSocket配置文件

package com.ax.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketAutoConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

 

4.WebSocket服務類

package com.ax.service;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/webSocket/{userId}")
public class WebSocketServer {
    //靜態變量,用來記錄當前在線連接數。
    private static int onlineCount = 0;

    private Session session;

    //concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
    private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();
    //與某個客戶端的連接會話,需要通過它來給客戶端發送數據
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();

    /**
     * @方法描述: 開啟socket
     * @return: void
     * @Author: carry
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        int maxSize = 200 * 1024;
        //  可以緩沖的傳入二進制消息的最大長度
        session.setMaxBinaryMessageBufferSize(maxSize);
        //  可以緩沖的傳入文本消息的最大長度
        session.setMaxTextMessageBufferSize(maxSize);
        this.session = session;
        //  加入set中
        webSockets.add(this);
        //  連接數加1
        addOnlineCount();
        //  把對應用戶id的session放到sessionPool中,用於單點信息發送
        sessionPool.put(userId, session);
        System.out.println("【websocket消息】 有新連接加入!用戶id" + userId + ",當前連接數為" + getOnlineCount());
    }

    /**
     * @方法描述: 關閉socket
     * @return: void
     * @Author: carry
     */
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        subOnlineCount();           //在線數減1
        System.out.println("【websocket消息】 連接斷開!當前連接數為" + getOnlineCount());
    }

    /**
     * @方法描述: 收到客戶端消息
     * @return: void
     * @Author: carry
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客戶端消息:" + message);
    }

    /**
     * @方法描述: 廣播消息全體發送
     * @return: void
     * @Author: carry
     */
    public void sendAllMessage(String message) {
        for (WebSocketServer webSocket : webSockets) {
            System.out.println("【websocket消息】廣播消息:" + message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @方法描述: 一對一單點消息
     * @return: void
     * @Author: carry
     */
    public void sendOneMessage(String userId, String message) {
        try {
            // 防止推送到客戶端的信息太多導致彈窗太快
//            Thread.sleep(500);
            System.out.println("用戶" + userId + "【websocket消息】單點消息:" + message);
            Session session = sessionPool.get(userId);
            if (session != null) {
                // getAsyncRemote是異步發送
                // 加鎖防止上一個消息還未發完下一個消息又進入了此方法,防止多線程中同一個session多次被調用報錯
                synchronized (session) {
                    session.getAsyncRemote().sendText(message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @方法描述: 發生錯誤時調用
     * @return: void
     * @Author: carry
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("發生錯誤");
        error.printStackTrace();
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM