最近的項目中使用ws 長連接來接收和發送消息, 直接上代碼
import * as SockJS from "sockjs-client"; import Stomp from "stompjs";
connection() { if (this.clientSubscribe) { console.log('unsubscribe') this.clientSubscribe.unsubscribe() } const token = ""; // const TENANT_ID = getStore({name: 'tenantId'}) ? getStore({name: 'tenantId'}) : '1' const headers = { Authorization: "Bearer " + token, chatSessionId: this.chatBaseInfo.chatSessionId, tempToken: this.chatBaseInfo.tempToken, }; // 建立連接對象 this.socket = new SockJS("/bot/ws"); // 連接服務端提供的通信接口,連接以后才可以訂閱廣播消息和個人消息 //獲取STOMP子協議的客戶端對象 this.stompClient = Stomp.over(this.socket); //this.stompClient.debug = true //向服務器發起websocket連接 this.stompClient.connect( headers, () => { this.isConnection = false this.successCallback() }, () => { console.log('斷開重新連接') this.isConnection = true console.log( this.stompClient) if (this.env === "WEB") { setTimeout(() => { this.connection() },2000) } //this.reconnect(this.successCallback); } ); },
successCallback(){ this.clientSubscribe = this.stompClient.subscribe( "/x99/receive/" + this.chatBaseInfo.chatSessionId, (msg) => { // 訂閱服務端提供的某個topic; // 處理接收的數據 } ); },
遇到的問題是 在ios手機端 鎖屏的情況下 會把websocket 斷開 解決的方案是
mounted() { document.addEventListener('visibilitychange', () => { if (!document.hidden) {//頁面呼出 if (this.stompClient&&!this.stompClient.connected) { this.connection() } } }) },
注意 1.在web 端是沒有這個事件的 所以在重新連接的地方加了判斷 是web 端用了定時器去沖新連接
2.在重新連接前需要判斷之前的訂閱是不是存在 存在的話先取消訂閱,
if (this.clientSubscribe) {
this.clientSubscribe.unsubscribe()
}