js 在vue2中使用ws
main.js中
import store from './store'
const app = new Vue({
store,
...App
})
store/index.js中
import Vue from "vue";
import Vuex from "vuex";
import * as actions from "./actions";
import * as mutations from "./mutations";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
websocket: null,
messageHandlers: [], // 存储消息处理函数
},
actions,
mutations,
});
export default store;
store/actions.js
// 初始化 WebSocket 连接
export const initWebSocket = ({ commit, state }) => {
const ws = new WebSocket(
"ws://testh5tp.rqw8.com:9508?type=app&uid=" + uni.getStorageSync("uid")
);
ws.onmessage = (event) => {
console.log("消息");
console.log(event.data);
// 分发消息给已订阅的处理函数
for (const handler of state.messageHandlers) {
handler.fun(event.data, handler.t)
}
};
const pingInterval = 30000; // 30秒的心跳间隔
// 定时发送Ping帧
const pingIntervalId = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
type: "HeartBeat",
id: uni.getStorageSync("uid"),
msg: "HeartBeat",
})
);
}
}, pingInterval);
ws.onclose = (event) => {
clearInterval(pingIntervalId);
// 根据需要处理连接关闭事件
};
commit("setWebSocket", ws);
};
store/mutations.js
export const msgHandlers = (state, e)=> {
state.messageHandlers(e);
}
export const setWebSocket = (state,ws)=> {
state.websocket = ws;
}
export const addMessageHandler = (state, handler) => {
console.log(handler)
state.messageHandlers.push({
fun : handler.fun,
t: handler.t
});
};
export const removeMessageHandler = (state, handler) => {
console.log('删除')
const index = state.messageHandlers.indexOf(handler);
if (index !== -1) {
state.messageHandlers.splice(index, 1);
}
};
页面中引入
import { mapActions,mapMutations } from 'vuex';
// 定义一个onmessage
handleMessage: (data, t) => {
let that = t;
const message = JSON.parse(data);
if (message.type == 'notice') {
// 自己写逻辑
}
},
// 页面变更事件,添加这里
// 载入本页面的onmessage事件
this.$store.commit('addMessageHandler', {
fun: this.handleMessage,
t: this
});
// 如果没有初始化ws,就连接ws
if (!this.$store.state.websocket) {
this.$store.dispatch('initWebSocket');
}
// 页面消失事件,或者离开
this.$store.commit('removeMessageHandler', this.handleMessage);
// methods中添加
...mapMutations(['addMessageHandler', 'removeMessageHandler']),
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭