效果:
class websocketMessage {constructor(params) {this.params = params; // 传入的参数this.socket = null;this.lockReconnect = false; // 重连的锁this.socketTimer = null; // 心跳this.lockTimer = null; // 重连this.timeout = 3000; // 发送消息this.callbacks = []; // 存储外部的回调函数// this.init(); // websocket 初始化}/*** @description: websocket 初始化* @return {*}*/init() {if (!("WebSocket" in window)) {console.warn("当前浏览器不支持 WebSocket");return;}this.lockReconnect = false;this.socket = new WebSocket(this.params.ws);this.socket.onopen = this.open.bind(this);this.socket.onmessage = this.onMessage.bind(this);this.socket.onerror = this.error.bind(this);// this.socket.onclose = this.close.bind(this);}/*** @description: websocket 已连接* @return {*}*/open() {console.log(`${this.params.ws}:WebSocket已连接。`);}/*** @description: 监听接收消息* @param {*} event* @return {*}*/onMessage({data}) {// 判断是否开启心跳if (this.params.heart) {this.socketTimer && clearTimeout(this.socketTimer);this.socketTimer = setTimeout(() => {this.socket.send(JSON.stringify(this.params.heart.data));}, 3000);}// 如果开启心跳,过滤掉心跳的数据if (data === this.params?.heart?.data) {return;}// 将消息传递给所有注册的回调函数this.callbacks.forEach((callback) => callback(typeof data === 'string' ? data : JSON.parse(data)));}/*** @description: 注册消息回调函数* @param {*} callback 回调函数* @return {*}*/message(callback) {if (typeof callback === "function") {this.callbacks.push(callback);} else {console.warn("注册的回调必须是一个函数");}}/*** @description: 发送消息* @param {*} msg* @return {*}*/send(msg) {if (!this.socket) {return;}let timer = null;clearTimeout(timer);timer = setTimeout(() => {if (this.socket?.readyState === 1) {this.socket.send(JSON.stringify(msg));clearTimeout(timer);} else {this.send(msg);}}, 50);}/*** @description: 连接发送错误的时候,输出信息* @param {*} e 错误消息* @return {*}*/error(e) {this.socket = null;console.log(`${this.params.ws}:WebSocket正在重新连接`, e);this.reconnect();}/*** @description: 关闭 websocket 连接* @return {*}*/close() {this.socket = null;this.lockReconnect = true;this.callbacks = []; // 清除回调clearTimeout(this.lockTimer);clearTimeout(this.socketTimer);this.socket?.onclose();console.log(`${this.params.ws}:WebSocket连接已关闭`);}/*** @description: 重新连接 websocket* @return {*}*/reconnect() {if (this.lockReconnect) {return;}this.lockReconnect = true;clearTimeout(this.lockTimer);this.lockTimer = setTimeout(() => {this.init();}, this.timeout);}
}// 调用:
let socket = new websocketMessage({ws: "wss://toolin.cn/echo",
});socket.init();// 注册消息处理回调
socket.message((data) => {console.log("接收到的消息:", data);
});// 发送登录消息
socket.send({type: "login",data: {userId: "123",},
});
setTimeout(() => {// 发送登录消息socket.send({type: "sadfasd",data: {userId: "sadf",},});
}, 5000)
setTimeout(() => {// 发送登录消息socket.send({type: "20000",data: {userId: "2",},});
}, 2000)