春风项目四线(合箱线、总装线)
wujian
2024-03-16 059083082a6d284821b70eb7bb6805763014c402
提交 | 用户 | 时间
059083 1 //需求:在JavaScript中实现WebSocket连接失败后3分钟内尝试重连3次的功能,你可以设置一个重连策略,
W 2 //     包括重连的间隔时间、尝试次数以及总时间限制。
3
4 /**
5  * @param {string} url  Url to connect
6  * @param {number} maxReconnectAttempts Maximum number of times
7  * @param {number} reconnect Timeout
8  * @param {number} reconnectTimeout Timeout
9  *
10  */
11 class WebSocketReconnect {
12
13   constructor(url, maxReconnectAttempts = 3, reconnectInterval = 20000, maxReconnectTime = 180000) {
14     this.url = url
15     this.maxReconnectAttempts = maxReconnectAttempts
16     this.reconnectInterval = reconnectInterval
17     this.maxReconnectTime = maxReconnectTime
18     this.reconnectCount = 0
19     this.reconnectTimeout = null
20     this.startTime = null
21     this.socket = null
22
23     this.connect()
24   }
25
26   //连接操作
27   connect() {
28     console.log('connecting...')
29     this.socket = new WebSocket(this.url)
30
31     //连接成功建立的回调方法
32     this.socket.OnOpen = () => {
33       console.log('WebSocket Connection Opened!')
34       this.clearReconnectTimeout()
35       this.reconnectCount = 0
36     }
37     //连接关闭的回调方法
38     this.socket.OnClose = (event) => {
39       console.log('WebSocket Connection Closed:', event)
40       this.handleClose()
41     }
42     //连接发生错误的回调方法
43     this.socket.OnError = (error) => {
44       console.error('WebSocket Connection Error:', error)
45       this.handleClose() //重连
46     }
47   }
48
49   //断线重连操作
50   handleClose() {
51     if (this.reconnectCount < this.maxReconnectAttempts && (this.startTime === null ||
52       Date.now() - this.startTime < this.maxReconnectTime)) {
53       this.reconnectCount++
54       console.log(`正在尝试重连 (${this.reconnectCount}/${this.maxReconnectAttempts})次...`)
55       this.reconnectTimeout = setTimeout(() => {
56         this.connect()
57       }, this.reconnectInterval)
58
59       if (this.startTime === null) {
60         this.startTime = Date.now()
61       }
62     } else {
63       console.log('超过最大重连次数或重连时间超时,已放弃连接!Max reconnect attempts reached or exceeded max reconnect time. Giving up.')
64       this.reconnectCount = 0 // 重置连接次数0
65       this.startTime = null // 重置开始时间
66     }
67   }
68
69   //清除重连定时器
70   clearReconnectTimeout() {
71     if (this.reconnectTimeout) {
72       clearTimeout(this.reconnectTimeout)
73       this.reconnectTimeout = null
74     }
75   }
76
77   //关闭连接
78   close() {
79     if (this.socket && this.socket.readyState === WebSocket.OPEN) {
80       this.socket.close()
81     }
82     this.clearReconnectTimeout()
83     this.reconnectCount = 0
84     this.startTime = null
85   }
86 }
87
88 // WebSocketReconnect 类封装了WebSocket的连接、重连逻辑。
89 // maxReconnectAttempts 是最大重连尝试次数。
90 // reconnectInterval 是每次重连尝试之间的间隔时间。
91 // maxReconnectTime 是总的重连时间限制,超过这个时间后不再尝试重连。
92 // reconnectCount 用于记录已经尝试的重连次数。
93 // startTime 用于记录开始重连的时间。
94 // connect 方法用于建立WebSocket连接,并设置相应的事件监听器。
95 // handleClose 方法在WebSocket连接关闭或发生错误时被调用,根据条件决定是否尝试重连。
96 // clearReconnectTimeout 方法用于清除之前设置的重连定时器。
97 // close 方法用于关闭WebSocket连接,并清除重连相关的状态。
98
99 // 使用示例
100 // const webSocketReconnect = new WebSocketReconnect('ws://your-websocket-url')
101 // 当不再需要WebSocket连接时,可以调用close方法
102 // webSocketReconnect.close();
103
104 export default WebSocketReconnect
105