vue3使用vue-native-websocket-vue3通訊
- 插件使用
- 一、啟用Vuex集成
- 1.在mian.js中
- 2.store/index.js文件中
- 3.要websocket使用的頁面
- 二、啟用Piain集成
- 1.在mian.js中
- 2.根目錄下創建store文件夾,分別創建PiniaType.ts,store.ts,useSocketStore.ts文件
- ①.PiniaType.ts文件
- ②.store.ts文件
- ③.useSocketStore.ts文件
- 3.要websocket使用的頁面
插件使用
vue-native-websocket-vue3
安裝
npm install vue-native-websocket-vue3 --save
如果你的項目啟用了TypeScript,則在main.ts文件中導入并使用插件。
沒有啟用就在main.js中導入并使用。
使用插件時,第二個參數為必填項,是你的websocket服務端連接地址。
插件必須依賴于Vuex或者pinia任選其一即可。
import VueNativeSock from "vue-native-websocket-vue3";// 使用VueNativeSock插件,并進行相關配置
app.use(VueNativeSock,"");
一、啟用Vuex集成
1.在mian.js中
import VueNativeSock from "vue-native-websocket-vue3";
import store from "/@/store";
app.use(VueNativeSock, '你的websocket服務端連接地址', {// 啟用pinia集成 | enable pinia integrationstore: store,// 數據發送/接收使用使用jsonformat: "json",// 開啟手動調用 connect() 連接服務器connectManually: true,// 開啟自動重連reconnection: true,// 嘗試重連的次數reconnectionAttempts: 5,// 重連間隔時間reconnectionDelay: 3000
});
export default app;
2.store/index.js文件中
import { createStore } from "vuex";
import main from "../main";
export default createStore({state() {return {socket: {// 連接狀態isConnected: false,// 消息內容message: "",// 重新連接錯誤reconnectError: false,// 心跳消息發送時間heartBeatInterval: 50000,// 心跳定時器heartBeatTimer: 0}};},mutations: {// 連接打開SOCKET_ONOPEN(state, event) {main.config.globalProperties.$socket = event.currentTarget;state.socket.isConnected = true;// 連接成功時啟動定時發送心跳消息,避免被服務器斷開連接state.socket.heartBeatTimer = window.setInterval(() => {const message = "心跳消息";state.socket.isConnected &&main.config.globalProperties.$socket.sendObj({code: 200,msg: message});}, state.socket.heartBeatInterval);},// 連接關閉SOCKET_ONCLOSE(state, event) {state.socket.isConnected = false;// 連接關閉時停掉心跳消息clearInterval(state.socket.heartBeatTimer);state.socket.heartBeatTimer = 0;console.log("連接已斷開: " + new Date());console.log(event);},// 發生錯誤SOCKET_ONERROR(state, event) {console.error(state, event);},// 收到服務端發送的消息SOCKET_ONMESSAGE(state, message) {state.socket.message = message;},// 自動重連SOCKET_RECONNECT(state, count) {console.info("消息系統重連中...", state, count);},// 重連錯誤SOCKET_RECONNECT_ERROR(state) {state.socket.reconnectError = true;}}
});
3.要websocket使用的頁面
插件暴露的函數
send 發送非json類型的數據(使用插件時不能啟用JSON消息傳遞)
sendObj 發送json類型的數據(必須在使用插件時啟用JSON消息傳遞)
$connect 連接websocket服務器(必須在使用插件時啟用手動管理連接選項)
onmessage 收到服務端推送消息時的監聽
$disconnect 斷開websocket連接移除消息監聽
delete proxy.$socket.onmessage
<script setup>
import { onMounted, getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
onMounted(()=>{proxy.$disconnect();//斷開連接proxy.$connect(`你的websocket服務端連接地址`);//連接websocket//收消息proxy.$socket.onmessage = res => {// console.log(res, "我收到的消息");};// 調用send方法,以字符串形式發送數據proxy.$socket.send('some data');// 如果fomat配置為了json,即可調用sendObj方法來發送數據proxy.$socket.sendObj({ msg: 'data'} );
})
</script>
二、啟用Piain集成
1.在mian.js中
import { useSocketStoreWithOut } from "/@/store/useSocketStore";
import VueNativeSock from "vue-native-websocket-vue3";
const piniaSocketStore = useSocketStoreWithOut(app);
app.use(VueNativeSock, `你的websocket服務端連接地址`, {// 啟用pinia集成 | enable pinia integrationstore: piniaSocketStore,// 數據發送/接收使用使用jsonformat: "json",// 開啟手動調用 connect() 連接服務器connectManually: true,// 開啟自動重連reconnection: true,// 嘗試重連的次數reconnectionAttempts: 5,// 重連間隔時間reconnectionDelay: 3000
});
2.根目錄下創建store文件夾,分別創建PiniaType.ts,store.ts,useSocketStore.ts文件
①.PiniaType.ts文件
export type SocketStore = {// 連接狀態isConnected: boolean;// 消息內容message: string;// 重新連接錯誤reconnectError: boolean;// 心跳消息發送時間heartBeatInterval: number;// 心跳定時器heartBeatTimer: number;
};
export type socketType = {$connect: () => void;
};
②.store.ts文件
import { createPinia } from "pinia";
import { App } from "vue";
const store = createPinia();
export function setupStore(app: App<Element>) {app.use(store);
}
export { store };
③.useSocketStore.ts文件
import { App } from "vue";
import { defineStore } from "pinia";
import { setupStore } from "./store";
import { SocketStore } from "./PiniaType";
export const useSocketStore = (app: App<Element>) => {return defineStore({id: "socket",state: (): SocketStore => ({// 連接狀態isConnected: false,// 消息內容message: "",// 重新連接錯誤reconnectError: false,// 心跳消息發送時間heartBeatInterval: 50000,// 心跳定時器heartBeatTimer: 0}),actions: {// 連接打開SOCKET_ONOPEN(event: any) {console.log("successful websocket connection");app.config.globalProperties.$socket = event.currentTarget;this.isConnected = true;// 連接成功時啟動定時發送心跳消息,避免被服務器斷開連接this.heartBeatTimer = window.setInterval(() => {const message = "心跳消息";this.isConnected &&app.config.globalProperties.$socket.sendObj({code: 200,msg: message});}, this.heartBeatInterval);},// 連接關閉SOCKET_ONCLOSE(event: any) {this.isConnected = false;// 連接關閉時停掉心跳消息window.clearInterval(this.heartBeatTimer);this.heartBeatTimer = 0;console.log("連接已斷開: " + new Date());console.log(event);},// 發生錯誤SOCKET_ONERROR(event: any) {console.error(event);},// 收到服務端發送的消息SOCKET_ONMESSAGE(message: any) {this.message = message;},// 自動重連SOCKET_RECONNECT(count: any) {console.info("消息系統重連中...", count);},// 重連錯誤SOCKET_RECONNECT_ERROR() {this.reconnectError = true;}}})();
};
// Need to be used outside the setup
export function useSocketStoreWithOut(app: App<Element>) {setupStore(app);return useSocketStore(app);
}
3.要websocket使用的頁面
插件暴露的函數
send 發送非json類型的數據(使用插件時不能啟用JSON消息傳遞)
sendObj 發送json類型的數據(必須在使用插件時啟用JSON消息傳遞)
$connect 連接websocket服務器(必須在使用插件時啟用手動管理連接選項)
onmessage 收到服務端推送消息時的監聽
$disconnect 斷開websocket連接移除消息監聽
delete proxy.$socket.onmessage
<script setup>
import { onMounted, getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
onMounted(()=>{proxy.$disconnect();//斷開連接proxy.$connect(`你的websocket服務端連接地址`);//連接websocket//收消息proxy.$socket.onmessage = res => {// console.log(res, "我收到的消息");};// 調用send方法,以字符串形式發送數據proxy.$socket.send('some data');// 如果fomat配置為了json,即可調用sendObj方法來發送數據proxy.$socket.sendObj({ msg: 'data'} );
})
</script>