-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebSocketClient.js
222 lines (187 loc) · 6.93 KB
/
WebSocketClient.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
const EventEmitter = nativeRequire('events')
const WebSocket = nativeRequire('ws');
class WebSocketClient extends EventEmitter {
constructor(url, options = {}) {
super();
this.url = url;
this.reconnectInterval = options.reconnectInterval || 2000;
this.maxReconnectAttempts = options.maxReconnectAttempts || 10;
this.responseTimeout = options.responseTimeout || 5000;
this.socket = null;
this.reconnectAttempts = 0;
this.shouldReconnect = false;
this.isReconnecting = false;
this.messageQueue = [];
this.processingQueue = false;
}
connect() {
return new Promise((resolve, reject) => {
this.socket = new WebSocket(this.url)
this.socket.onopen = () => this.onOpen(resolve);
this.socket.onerror = (event) => {
const errorCode = event.error?.code || event?.code || "UNKNOWN";
switch (errorCode) {
case 'ECONNREFUSED':
this.shouldReconnect = true;
this.reconnect();
break;
default:
this.onError(event, reject);
}
}
this.socket.onmessage = (event) => this.onMessage(event);
this.socket.onclose = (event) => this.onClose(event);
});
}
async reconnect() {
if (this.isReconnecting) return;
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.error("Max reconnect attempts reached");
this.shouldReconnect = false;
this.cleanupSocket();
this.emit("reconnect_failed");
return;
}
this.isReconnecting = true;
this.reconnectAttempts++;
console.log(`Reconnecting (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
await new Promise((resolve) => setTimeout(resolve, this.reconnectInterval));
try {
await this.connect();
console.log("Reconnected successfully");
this.reconnectAttempts = 0;
this.emit("reconnect_success");
}
catch (error) {
console.error("Reconnect failed:", error);
this.reconnect();
}
finally {
this.isReconnecting = false;
}
}
cleanupSocket() {
console.log("Cleaning up WebSocket client");
// Close the existing socket, if any
if (this.socket) {
this.socket.removeAllListeners(); // Remove any lingering event listeners
if (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING) {
this.socket.close();
}
this.socket = null; // Dereference the socket
}
// Reset state variables
this.isReconnecting = false;
this.reconnectAttempts = 0;
this.shouldReconnect = false;
this.processingQueue = false;
// Reject pending promises in the message queue
while (this.messageQueue.length) {
const { reject } = this.messageQueue.shift();
reject(new Error("WebSocket closed during message queue processing - dumping message"));
}
// Emit a cleanup or failure event, if necessary
this.emit("cleanup");
}
onOpen(resolve) {
console.log("WebSocket connection opened");
this.reconnectAttempts = 0;
this.emit("open");
resolve();
this.processingQueue = false;
this._processQueue();
}
onError(error, reject) {
console.error("WebSocket connection error:", error.error.code, error.message);
this.emit("error", error);
if (reject) reject(error);
if (this.shouldReconnect) {
this.reconnect()
}
}
onMessage(event) {
const message = JSON.parse(event.data);
console.log("Message received:", message);
if (message.id) {
this.emit(`response:${message.id}`, message);
}
else {
this.emit("message", message);
}
}
onClose(event) {
console.warn("WebSocket connection closed:", event.code, event.reason);
this.emit("close", event);
if (this.shouldReconnect || event.code !== 1000) {
if (!this.isReconnecting) {
this.shouldReconnect = true;
this.reconnect();
}
this.isReconnecting = false;
}
else {
this.cleanupSocket();
}
}
async _processQueue() {
if (this.processingQueue || !this.messageQueue.length) return;
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
console.log("WebSocket not open, deferring queue processing...");
return;
}
this.processingQueue = true;
try {
while (this.messageQueue.length) {
const { payload, id, resolve, reject } = this.messageQueue.shift();
try {
this.socket.send(JSON.stringify(payload));
console.log("Message sent:", payload);
if (id) {
const responseEvent = `response:${id}`;
const response = await new Promise((res, rej) => {
const timeout = setTimeout(() => {
this.off(responseEvent, res);
rej(new Error(`Timeout waiting for response to message id: ${id}`));
}, this.responseTimeout);
this.once(responseEvent, (message) => {
clearTimeout(timeout);
res(message)
});
})
resolve(response)
}
else {
try {
await new Promise((response) => this.once("message", response));
resolve()
} catch(e) {
console.error(e);
}
}
}
catch (error) {
reject(error)
}
}
}
catch (globalError) {
console.error("Queue processing error:", globalError);
}
finally {
this.processingQueue = false;
}
}
send(message, id = null) {
return new Promise((resolve, reject) => {
const payload = id ? { id, ...message } : { ...message };
this.messageQueue.push({ payload, id, resolve, reject });
this._processQueue();
});
}
close() {
this.shouldReconnect = false;
this.cleanupSocket();
console.log("WebSocket closed")
}
}
module.exports = WebSocketClient;