jswebsocket⼼跳检测,断开重连,超时重连 1function longSock(url, fn, intro = '') {
2 let lockReconnect = false//避免重复连接
3 let timeoutFlag = true
4 let timeoutSet = null
5 let reconectNum = 0
6 const timeout = 30000 //超时重连间隔
websocket和socket7 let ws
8function reconnect() {
9if (lockReconnect) return
10 lockReconnect = true
11//没连接上会⼀直重连,设置延迟避免请求过多
12if (reconectNum < 3) {
13 setTimeout(function() {
14 timeoutFlag = true
15 createWebSocket()
16 console.info(`${intro}正在重连第${reconectNum + 1}次`)
17 reconectNum++
18 lockReconnect = false
19 }, 5000) //这⾥设置重连间隔(ms)
20 }
21 }
22//⼼跳检测
23 const heartCheck = {
24 timeout: 5000, //毫秒
25 timeoutObj: null,
26 serverTimeoutObj: null,
27 reset: function() {
28 clearInterval(this.timeoutObj)
29 clearTimeout(this.serverTimeoutObj)
30return this
31 },
32 start: function() {
33 const self = this
34 let count = 0
35this.timeoutObj = setInterval(() => {
36if (count < 3) {
37if (ws.readyState === 1) {
38 ws.send('HeartBeat')
39 console.info(`${intro}HeartBeat第${count + 1}次`)
40 }
41 count++
42 } else {
43 clearInterval(this.timeoutObj)
44 count = 0
45if (ws.readyState === 0 && ws.readyState === 1) {
46 ws.close()
47 }
48 }
49 }, self.timeout)
50 }
51 }
52 const createWebSocket = () => {
53 console.info(`${intro}创建11`)
54 timeoutSet = setTimeout(() => {
55if (timeoutFlag && reconectNum < 3) {
56 console.info(`${intro}重连22`)
57 reconectNum++
58 createWebSocket()
59 }
60 }, timeout)
61 ws = new WebSocket(url)
62
63 ws.onopen = () => {
64 reconectNum = 0
65 timeoutFlag = false
66 clearTimeout(timeoutSet)
67 set().start()
68 }
69 ws.onmessage = evt => {
70 set().start()
71// console.info(evt);
72if(evt.data === 'HeartBeat') return
73 fn(evt, ws)
74 }
75 ws.onclose = e => {
76 console.info(`${intro}关闭11`, e.code)
77if (e.code !== 1000) {
78 timeoutFlag = false
79 clearTimeout(timeoutSet)
80 reconnect()
81 } else {
82 clearInterval(heartCheck.timeoutObj)
83 clearTimeout(heartCheck.serverTimeoutObj)
84 }
85 }
86 ws.onerror = function() {
87 console.info(`${intro}错误11`)
88 reconnect() //重连
89 }
90 }
91 createWebSocket()
92return ws
93 }
94 export default longSock
1//⽅法调⽤
2 const handler = (evt, ws) => {
3//evt 是 websockett数据
4//ws 是请求名称,⽅便关闭websocket
5 }
6
7 const wssCenter = createSocket(`wss://url`, handler, '接待中⼼-⼩卡⽚') 8
9
10
11 wssCenter.close(); //断开连接
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论