WebSocket的简单使用

WebSocket的简单使用

 ws_ht() {
let url = window._CONFIG['wsURL']
//console.log('后台WS开始连接')
// 实例化socket
this.socket_ht = new WebSocket(url)
// 监听socket连接
this.socket_ht.onopen = this.wsopen_ht
// 监听socket错误信息
this.socket_ht.onerror = this.wserror_ht
// 监听socket消息
this.socket_ht.onmessage = this.wsgetMessage_ht
// 关闭socket连接
this.socket_ht.onclose = this.wsclose_ht
},

wsopen_ht(){
//console.log('后台ws连接成功')
}

wserror_ht(){
//console.log('后台ws连接错误')
this.reconnect()//重连的方法
}

wsgetMessage_ht(wsMessage){
//console.log('wsMessage')
if(wsMessage.data == '0xA'){
//收到消息后重新设置心跳检测
setTimeout(() => {
this.heartCheck()
}, 30000)
}
}

wsclose_ht(){
//console.log('后台ws连接成功')
this.reconnect()//重连的方法
}

//ws重连功能
reconnect(){
let that = this
if (that.lockReconnect) return
that.lockReconnect = true
//没连接上会一直重连,设置延迟避免请求过多
setTimeout(function() {
that.ws_ht()
that.lockReconnect = false
}, 6000)
}

//心跳检测
heartCheck(){、
let that = this
let sendTimeoutObj = null
let serverTimeoutObj = null
//清空定时器
sendTimeoutObj && clearTimeout(sendTimeoutObj)
serverTimeoutObj && clearTimeout(serverTimeoutObj)
sendTimeoutObj = setTimeout(function() {
that.socket_ht.send(that.ping_str)
serverTimeoutObj = setTimeout(function() {
that.socket_ht.onclose
}, 3000)
}, 3000)
}

一、实际需要的参数只有url,为后端建立ws的地址。

image-20221025110024065

二、打印出websocket的实例可以看出里面自带有四个属性:onopen=>onmessage=>onerror=>onclose

WebSocket.onclose

用于指定连接关闭后的回调函数。

WebSocket.onerror

用于指定连接失败后的回调函数。

WebSocket.onmessage

用于指定当从服务器接受到信息时的回调函数。

WebSocket.onopen

用于指定连接成功后的回调函数。

三、另外还有一个readyState,值有0\1\2\3。

0 (
WebSocket.CONNECTING
)
正在连接中
1 (
WebSocket.OPEN
)
已经连接并且可以通讯
2 (
WebSocket.CLOSING
)
连接正在关闭
3 (
WebSocket.CLOSED
)
连接已关闭或者没有连接成功

四、方法有两个。

WebSocket.close([code[, reason\]])

关闭当前链接。

WebSocket.send(data)

对要传输的数据进行排队。

五、保证链接稳定性

1、进行重连:

在出现error后调用重连函数,进行重连。

2、心跳机制:

websocket规范定义了心跳机制,一方可以通过发送ping(opcode 0x9)消息给另一方,另一方收到ping后应该尽可能快的返回pong(0xA)。

心跳机制是用于检测连接的对方在线状态,因此如果没有心跳,那么无法判断一方还在连接状态中,一些网络层比如 nginx 或者浏览器层会主动断开连接,检测到 open 事件后,启动一个定时任务,比如浏览器中,每次发送数据 0x9 给服务端,而服务端返回 0xA 作为响应;心跳的定时任务一般是相隔 15-20 秒发送一次。

标签: Javascript

添加新评论