websocket根据事件名派发消息
class WebSocketX extends WebSocket {
/**
* 初始化构造
* @param {*} url
*/
constructor({ url }) {
super(url);
// this.url = url;
// eventBusObject :{'001':[callback,callback],'002':[callback,callback],}
this.eventBusObject = {};
this.watchWebSocketEvent();
}
watchWebSocketEvent() {
this.onopen = e => {
this.socketOnopen(e);
};
this.onerror = e => {
this.socketOnerror(e);
};
this.onclose = e => {
this.socketOnclose(e);
};
this.onmessage = e => {
this.socketOnmessage(e);
};
}
/**
* 连接成功
*/
socketOnopen(e) {
console.log("%cWBESOCKET::::::socketOnopen", "color:green");
}
/**
* 连接出错
*/
socketOnerror(e) {
console.log("%cWBESOCKET::::::socketOnerror", "color:red");
}
/**
* 连接已关闭
*/
socketOnclose(e) {
console.log("%cWBESOCKET::::::socketOnclose", "color:red");
// 连接重连
setTimeout(() => {
this.initWebSocket(this.url);
}, 2000);
}
/**
* 监听socket事件,广播回调注册的事件
* @param {*} e
*/
socketOnmessage(e) {
const resData = JSON.parse(e.data);
const key = resData.key;
if (this.eventBusObject[key]) {
// 广播回调事件
this.eventBusObject[key].forEach(callback => {
callback(resData);
});
}
}
/**
* 主动发送数据给服务器
* @param {*} data
*/
sendData(data) {
this.socket.send(JSON.stringify(data));
}
/**
* 添加监听的事件
* @param {*} key
* @param {*} callback
*/
addEventListener(key, callback) {
if (this.eventBusObject[key]) {
this.eventBusObject[key].push(callback);
} else {
this.eventBusObject[key] = [callback];
}
}
/**
* 移除监听的事件
* @param {*} key
* @param {*} callback
*/
removeEventListener(key, callback) {
if (this.eventBusObject[key]) {
const index = this.eventBusObject[key].findIndex(callback);
index !== -1 && this.eventBusObject[key].splice(index, 1);
}
}
}
export default WebSocketX;
感谢,老铁的阅读,如果喜欢的,帮忙点个👍,你的支持我是前进的动力++
网友评论