本文就实战中原生websocket
进行封装
封装
class WebsocketUtil {
constructor(url, time) {
this.is_open_socket = false; //避免重复连接
this.url = url; //地址
this.data = null;
this.userInfo = userInfo;
//心跳检测
this.timeout = time; //多少秒执行检测
this.heartbeatInterval = null; //检测服务器端是否还活着
this.reconnectTimeOut = null; //重连之后多久再次重连
try {
return this.connectSocketInit();
} catch (e) {
console.log("catch");
this.is_open_socket = false;
this.reconnect();
}
}
// 进入这个页面的时候创建websocket连接【整个页面随时使用】
connectSocketInit() {
this.socketTask = new WebSocket(this.url);
this.socketTask.onopen = () => {
clearTimeout(this.reconnectTimeOut);
clearTimeout(this.heartbeatInterval);
this.start();
this.is_open_socket = true;
// 注:只有连接正常打开中 ,才能正常收到消息
this.socketTask.onmessage = (res) => {
let opts = JSON.parse(res.data);
console.log("接收消息:", opts);
// 用于页面监听websocket消息
window.dispatchEvent(
new CustomEvent("onmessageWS", {
detail: {
data: opts,
},
})
);
};
};
// 这里仅是事件监听【如果socket关闭了会执行】
this.socketTask.onclose = () => {
console.log("已经被关闭了");
this.is_open_socket = false;
this.reconnect();
};
}
//发送消息
socketSend(value) {
// 注:只有连接正常打开中 ,才能正常成功发送消息
if (this.is_open_socket) {
console.log("发送传参:", value);
// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
this.socketTask.send(JSON.stringify(value));
}
}
//开启心跳检测
start() {
this.heartbeatInterval = setTimeout(() => {
let data = {value:"传输内容",method:"方法名称"};
this.socketSend(data);
}, this.timeout);
}
//重新连接
reconnect() {
//停止发送心跳
clearInterval(this.heartbeatInterval);
//如果不是人为关闭的话,进行重连
if (!this.is_open_socket) {
this.reconnectTimeOut = setTimeout(() => {
this.connectSocketInit();
}, 200);
}
}
}
export default WebsocketUtil;
使用方式
单页面使用
- 引入
import WebsocketUtil from "@/utils/websocket.js";
- 使用
let websocket = new WebsocketUtil("ws://xxx:3100/connect/websocket",5000)
// 发送消息
let data={value:"传输内容",method:"方法名称"}
websocket.send(JSON.stringify(data));
// 接收消息
window.addEventListener("onmessageWS", (res) => {
let opt = res.detail.data;
console.warn("接收到websocket消息通知:", opt);
});
全局使用
在main.vue页面引入并且挂载到Vue实例
//引入websocket封装
import WebsocketUtil from "@/utils/websocket.js";
//挂载到全局
Vue.prototype.$socket = new WebsocketUtil("ws://xxx:3100/connect/websocket",5000)
页面中调用
// 发送消息
let data={value:"传输内容",method:"方法名称"}
this.$socket.send(JSON.stringify(data));
// 接收消息
window.addEventListener("onmessageWS", (res) => {
let opt = res.detail.data;
console.warn("接收到websocket消息通知:", opt);
});
注意事项
//在测试环境时url可以写成 ws://xxx:3100/connect/websocket
new WebsocketUtil("ws://xxx:3100/connect/websocket",5000)
//如果发布正式版,域名为htts时,url一定要写成 wss://xxx:3100/connect/websocket
new WebsocketUtil("wss://xxx:3100/connect/websocket",5000)