// 初始化 let socketUrl = "ws://127.0.0.1/notification/1920102920123232"; // 也有加密的协议 let socketUrl = "wss://127.0.0.1/notification/1920102920123232"; let ws = new WebSocket(socketUrl);
WebSocket连接状态:要获取连接状态,可以通过带有值的 socket.readyState
属性
0
—— “CONNECTING”:连接还未建立,1
—— “OPEN”:通信中,2
—— “CLOSING”:连接关闭中,3
—— “CLOSED”:连接已关闭。
WebSocket四个事件:开发中监听这四个事件处理业务
open —— 建立连接
message —— 接收到数据
close —— 连接关闭
error —— 连接错误
ws.addEventListener("open",this.openHandle); ws.addEventListener("close",this.closeHandle); ws.addEventListener("message",this.messageHandle); ws.addEventListener("error",this.errorHandle);
WebSocket发送数据:
ws.send("ping");
WebSocket保持连接的两种方式
方法一:断开重连
在 socket的close方法中,监听到连接已关闭,就让重新连接
let ws = null; let timer = null; createSocket() { let socketUrl = `ws://127.0.0.1/notification/${userId}`; ws = new WebSocket(socketUrl); ws.addEventListener("open",this.openHandle); ws.addEventListener("close",this.closeHandle); ws.addEventListener("message",this.messageHandle); ws.addEventListener("error",this.errorHandle); }, openHandle() { console.log("socket连接成功") }, closeHandle() { console.log("socket已关闭") // 断开重连 this.restartWs(); }, messageHandle(e) { console.log("socket接收消息") console.log(e) this.unReaderNum = parseInt(e.data); }, errorHandle() { console.log("socket错误!!!") }, // 断开重连 restartWs() { console.log("socket连接失败,准备重连...") timer = setInterval(() => { this.createSocket(); if (ws && ws.readyState === 0) { clearInterval(timer); timer = null; } },2000) },
方法二:socket的心跳机制
open连接之后,写个定时器,每隔一段时间send数据,看连接是否活着