记录一次websocket封装的过程
在一个应用中,websocket一般都是以单例形式存在的,即在整个应用中,websocket实例始终保持唯一。但有时我们要用到websocket实例的时候,可能websocket还没实例化,所以要做成异步的形式来获取实例。
一、封装。先创建socket.ts文件
importEventEmitterfrom'events';//这里用到了events包 constee=newEventEmitter(); classWs{ privatewsUrl:string=''; privatesocket:WebSocket|undefined;//socket实例 privatelockReconnect:boolean=false;//重连锁 privatetimeout:NodeJS.Timeout|undefined; //初始化socket,一般在应用启动时初始化一次就好了,或者需要更换wsUrl publicinit(wsUrl:string){ this.wsUrl=wsUrl; this.createWebSocket(); } //获取socket实例 publicgetInstance():Promise{ returnnewPromise((resolve,reject)=>{ if(this.socket){ resolve(this.socket); }else{ ee.on('socket',(state:string)=>{ if(state==='success'){ resolve(this.socket); }else{ reject(); } }); } }); } //创建socket privatecreateWebSocket(){ try{ console.log('websocket开始链接'); constsocket=newWebSocket(this.wsUrl); socket.addEventListener('close',()=>{ console.log('websocket链接关闭'); this.socket=undefined; this.reconnect(); }); socket.addEventListener('error',()=>{ console.log('websocket发生异常了'); this.socket=undefined; this.reconnect(); }); socket.addEventListener('open',()=>{ //可在此进行心跳检测 //this.heartCheck.start(); console.log('websocketopen'); this.socket=socket; ee.emit('socket','success'); }); socket.addEventListener('message',(event)=>{ console.log('websocket接收到消息',event); }); }catch(e){ console.log('socketcatcherror',e); this.reconnect(); } } //重连 privatereconnect(){ if(this.lockReconnect){ return; } console.log('websocket正在重新连接'); this.lockReconnect=true; //没连接上会一直重连,设置延迟避免请求过多 this.timeout&&clearTimeout(this.timeout); this.timeout=setTimeout(()=>{ this.createWebSocket(); this.lockReconnect=false; },5000); } } exportdefaultnewWs();
二、引入并使用
importsocketfrom'@/utils/ws'; socket .getInstance() .then((ws)=>{ //这里的ws就是实例化后的websocket,可以直接使用websocket原生api console.log('getInstancews',ws); ws.addEventListener('message',(event)=>{ console.log('ws接收到消息',event); }); }) .catch(()=>{});
以上就是记录一次websocket封装的过程的详细内容,更多关于websocket封装的资料请关注毛票票其它相关文章!