websocket 工具类封装
export default class SocketService{
static instance=null;
static get Instance(){
if(!this.instance){
this.instance=new SocketService();
}
}
wx=null;
callBackMapping={};
connected=false;
sendRetryCount=0;
connectRetryCount=0;
connect(){
if(!window.WebSocket){
return console.log("您的浏览器不支持websocket")
}
let url="ws:127.0.0.1:8888/websocket";
this.ws=new WebSocket(url)
this.ws.onopen=()=>{
console.log("连接成功")
this.connected=true;
this.connectRetryCount=0;
};
this.ws.onclose=()=>{
console.log("链接失败")
this.connected=false;
this.connectRetryCount++;
setTimeout(()=>{
this.connect();
},500*this.connectRetryCount);
};
}
//回调函数的注册
registerCallBack(socketType,callBack){
this.callBackMapping[socketType]=callBack;
}
//取消回调函数注册
unRegisterCallBack(socketType){
this