**export default ({ store }, inject) => {
let userId, ws, heartbeat;
// 这里封装了一个实现心跳的构造函数
// 同时传入一个回调函数给定时器执行
function Heartbeat(func, interval = 3000) {
// 保存定时器
this.timer = null;
// // 定时器间隔
// 心跳启动
this.start = function () {
clearInterval(this.timer);
this.timer = setInterval(func, interval);
};
// 停止
this.stop = function () {
clearInterval(this.timer);
};
}
function WebSocketInit(id) {
ws = new WebSocket(process.env.wsURL + "?userId=" + id)
userId = id
// 有新消息时触发
ws.onmessage = function (e) {
console.log('服务器发来消息: ', e.data);
if (e.data == "success" || e.data == "pong") {
console.log(e.data);
return
}
const data = JSON.parse(e.data);
store.commit("utils/SetWSMsg", data);
if (data["noticeTitle"]) {
if (data["noticeType"] == 4) {
console.log(JSON.parse(data.noticeContent));
store.commit("login/SetUserInfo", JSON.parse(data.noticeContent));
} else {
store.commit("login/SetNoticeCount", { systemNoticeCount: 1 });
}
} else {
store.commit("login/SetNoticeCount", { interactiveNoticeCount: 1 });
}
};
// 发生错误触发
ws.onerror = function (e) {
console.log('连接错误: ', e);
};
// 连接关闭触发
ws.onclose = function (e) {
console.log('连接中断: ', e);
heartbeat !== undefined ? heartbeat.stop() : ''
};
// 在 WebSocket对象实例上追加方法
ws.sendHeartbeat = function () {
ws.send(JSON.stringify({ fromUserId: userId, info: "ping" }));
};
ws.onopen = function () {
// 连接后立即发一条消息刷存在感【必要】
this.send(JSON.stringify({ fromUserId: userId, info: "ping" }));
heartbeat = new Heartbeat(ws.sendHeartbeat);
heartbeat.start();
};
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
// 添加上 会出现弹窗,不添加则会静默执行回调函数内的任务,下面同这条类似作用,只是处理兼容问题
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
ws.close()
heartbeat.stop();
});
document.addEventListener("visibilitychange", function () {
if (document.visibilityState !== 'visible') {
ws.close()
heartbeat.stop();
}
});
}
//inject注入
inject("webScoket", { WebSocketInit });
};
**
nuxt中简单使用WebSocket
最新推荐文章于 2025-05-13 19:08:48 发布