vue使用SockJS實現webSocket通訊
阿新 • • 發佈:2020-08-14
先安裝 sockjs-client 和 stompjs
npm install sockjs-client
npm install stompjs
import SockJS from 'sockjs-client'; import Stomp from 'stompjs'; export default { data(){ return { stompClient:'', timer:'', } }, methods:{ initWebSocket() {this.connection(); let that= this; // 斷開重連機制,嘗試傳送訊息,捕獲異常發生時重連 this.timer = setInterval(() => { try { that.stompClient.send("test"); } catch (err) { console.log("斷線了: " + err); that.connection(); } },5000); }, connection() { // 建立連線物件 let socket = new SockJS('http://10.10.91.4:8081/ws'); // 獲取STOMP子協議的客戶端物件 this.stompClient = Stomp.over(socket); // 定義客戶端的認證資訊,按需求配置 let headers = { Authorization:'' }// 向伺服器發起websocket連線 this.stompClient.connect(headers,() => { this.stompClient.subscribe('/topic/public', (msg) => { // 訂閱服務端提供的某個topic console.log('廣播成功') console.log(msg); // msg.body存放的是服務端傳送給我們的資訊 },headers); this.stompClient.send("/app/chat.addUser", headers, JSON.stringify({sender: '',chatType: 'JOIN'}), ) //使用者加入介面 }, (err) => { // 連線發生錯誤時的處理函式 console.log('失敗') console.log(err); }); }, //連線 後臺 disconnect() { if (this.stompClient) { this.stompClient.disconnect(); } }, // 斷開連線 }, mounted(){ this.initWebSocket(); }, beforeDestroy: function () { // 頁面離開時斷開連線,清除定時器 this.disconnect(); clearInterval(this.timer); } }