先安裝 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);
}
}
轉載:紫藤蘿yu 的《vue使用SockJS實現webSocket通信》