1.结构WebSocket实例
var ws = new WebSocket('ws://localhost:8080');
2.以后实例的readyState 状态
WebSocket的四种状态CONNECTING:值为0,示意正在连接。OPEN:值为1,示意连贯胜利,能够通信了。CLOSING:值为2,示意连贯正在敞开。CLOSED:值为3,示意连贯曾经敞开,或者关上连贯失败。
3.实例属性回调函数
ws.onopen = (e)=> { console.log("连贯胜利")}ws.onmessage= (e)=> { console.log("接管音讯胜利")}ws.onoerror = (e)=> { console.log("连贯失败")}ws.onclose = (e)=> { console.log("连贯敞开")}
4. 重连
//重连 reConnection(){ console.log("从新连贯") if(this.lockReconnect){ return } this.lockReconnect = true if(this.timerReconnect) { clearTimeout(this.timerReconnect) } //没连上会始终重连, 设置迟延,防止申请过多 this.timerReconnect = setTimeout(() => { //setTimeout 到点了执行 this.createWebSocket() this.lockReconnect = false }, 5000); }
5. 监测心跳
heartCheck(){ console.log("监测心跳") if(this.timerHeart){ clearTimeout(this.timerHeart) } if(this.timerServerHeart){ clearTimeout(this.timerServerHeart) } this.timerHeart = setTimeout(() => { this.ws.send("are you weak") this.timerServerHeart = setTimeout(() => { // 断了 this.ws.close() }, 5000); this.lockReconnect = false }, 2000); }
6.残缺的封装代码———待欠缺后更新