1.构造一个WebSocket实例varws=newWebSocket('ws://localhost:8080');2、当前实例的readyState状态WebSocketCONNECTING的四种状态:值为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.Reconnect//重新连接reConnection(){console.log("Reconnect")if(this.lockReconnect){return}this.lockReconnect=trueif(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("areyouweak")this.timerServerHeart=setTimeout(()=>{//breakthis.ws.close()},5000);this.lockReconnect=false},2000);}6.完整包代码——完成后更新
