1.新建websocket.js文件夹,复制下面代码在创建js文件里。
import CryptoJS from "crypto-js"; //加密js,看项目需求是否引入
// 加密
function encrypt(word, keyStr) {
keyStr = "ev##hna4FNN!y6a4";
let key = CryptoJS.enc.Utf8.parse(keyStr);
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
}
class Person {
socket = null; //socket 初始化创建的socket对象
Times = null; //Times 定时器对象,用于关闭心跳倒计时
heartbeatTime = 1; //heartbeatTime 心跳倒计时秒
constructor() {}
//初始化
scoketInit() {
if (typeof WebSocket == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
var socketUrl;
switch (process.env.NODE_ENV) {
case "development":
socketUrl = "" //本地运行ws地址
break;
case "production":
socketUrl = "" //发布线上ws地址
break;
}
if (this.socket != null) {
this.socket.close();
this.socket = null;
}
this.socket = new WebSocket(socketUrl);
this.socket.onclose = function () {}
this.socket.onerror = function () {
// console.log("websocket错误。。。。");
};
}
}
// 清除scoket
scoketEmpty() {
this.socket = null;
this.Times = null;
this.heartbeatTime = 1;
}
socketOnopen() {
//打开链接事件
let that = this
return new Promise((resolve, reject) => {
that.socket.onopen = function () {
// console.log("websocket已打开");
resolve(that.socket)
};
})
}
//发送消息
sendMsg(data) {
this.socket.send(JSON.stringify({
"params": data
}))
}
//接收消息
receiveMsg(data) {
return this.socket
}
//发生错误
socketError(callback) {
let that = this
this.socket.onerror = function () {
console.log("socket 发生错误!");
callback()
};
}
//scoket 关闭
socketClose(callback) {
// callback 回调函数 当scoket发生关闭时通知调取页面
let that = this
this.socket.onclose = function () {
callback()
};
}
// 开启心跳
StartHeartbeat() {
let that = this
that.Times = setInterval(() => {
if (that.heartbeatTime <= 0) {
console.log("心跳时间倒计时 发送");
that.heartbeatTime = 26;
//encrypt 字段加密 通过定时器给服务器发送心跳
let data = encrypt(JSON.stringify({
cmdName: "heart",
param: {}
}));
that.sendMsg(data)
} else {
that.heartbeatTime = that.heartbeatTime - 1;
}
}, 1000);
}
//关闭心跳 //# scoket
closeHeartbeat() {
console.log("关闭心跳定时器");
this.socket.onclose()
this.socket = null;
this.heartbeatTime = 1;
clearInterval(this.Times);
}
}
export default Person;
2.vue页面使用
import Person from "@/assets/js/scoketClass";
const socket = new Person();
//引入同时new
export default {
mounted() {
socket.scoketEmpty(); //数据初始化
socket.scoketInit(); //socket初始化
this.scoketAdd(); //
},
methods(){
//手动链接
socketReconnection() {
socket.scoketEmpty();
socket.scoketInit();
this.scoketAdd();
},
socketAdd() {
console.log("websocket 函数执行");
let that = this;
//异步执行
socket.socketOnopen().then((resd) => {
console.log("websocket已连接");
that.isScoketLink = true;
let data = encrypt(
JSON.stringify({ cmdName: "systemManagement", param: {} })
);
socket.sendMsg(data);
//我的后端需求链接后首次发送信息后,才能获取消息
// start 开始心跳倒计时,
socket.StartHeartbeat();
//scoket 链接关闭
socket.socketClose(function () {
//网络波动或者其他原因导致的socket断开链接,回调方法可通知到当前页面
that.$notify.error({
title: "提示",
message: "聊天监控已断开链接!",
});
console.log("socket 断开链接!");
});
//scoket 发生错误
socket.socketError(function () {
//连接发生错误时候,回调可通知到当前页面
console.log("socket 发生错误!");
});
//接收消息
socket.receiveMsg().onmessage = (resMsg) => {
console.log("socket 接收消息!",resMsg);
};
});
},
beforeDestroy() {
// 离开页面关闭socket连接
socket.closeHeartbeat();
},
}
}
到这里就结束了,谢谢观看