Paul 5 years ago
parent
commit
5788c7740f
2 changed files with 115 additions and 45 deletions
  1. 37
    38
      example/main.ts
  2. 78
    7
      src/client.ts

+ 37
- 38
example/main.ts View File

2
 import { WebsocketError } from './error';
2
 import { WebsocketError } from './error';
3
 
3
 
4
 const url = 'ws://127.0.0.1:8081';
4
 const url = 'ws://127.0.0.1:8081';
5
-const client = new Client(
6
-  url,
7
-  new (class {
8
-    public onOpen(): void {
9
-      client
10
-        .ping({})
11
-        .then(
12
-          (res: string): void => {
13
-            console.log('ping sucessful:', res);
14
-          },
15
-        )
16
-        .catch(
17
-          (reason: WebsocketError): void => {
18
-            console.log('ping error:', reason.code, reason.msg);
19
-          },
20
-        );
5
+const client = new Client(url, {
6
+  onOpen(): void {
7
+    client
8
+      .ping({})
9
+      .then(
10
+        (res: string): void => {
11
+          console.log('ping sucessful:', res);
12
+        },
13
+      )
14
+      .catch(
15
+        (reason: WebsocketError): void => {
16
+          console.log('ping error:', reason.code, reason.msg);
17
+        },
18
+      );
21
 
19
 
22
-      client
23
-        .request('/v1/healthy/a', {})
24
-        .then(
25
-          (res: string): void => {
26
-            console.log('request successful:', res);
27
-          },
28
-        )
29
-        .catch(
30
-          (reason: WebsocketError): void => {
31
-            console.log('request error:', reason.code, reason.msg);
32
-          },
33
-        );
34
-    }
20
+    client
21
+      .request('/v1/healthy', {})
22
+      .then(
23
+        (res: string): void => {
24
+          console.log('request successful:', res);
25
+        },
26
+      )
27
+      .catch(
28
+        (reason: WebsocketError): void => {
29
+          console.log('request error:', reason.code, reason.msg);
30
+        },
31
+      );
32
+  },
35
 
33
 
36
-    public onClose(ev: Event): void {
37
-      console.log('connection error', ev);
38
-      console.log(ev);
39
-    }
34
+  onClose(ev: Event): void {
35
+    console.log('connection error', ev);
36
+    console.log(ev);
37
+  },
40
 
38
 
41
-    public onError(): void {
42
-      console.log('close connection');
43
-    }
44
-  })(),
45
-);
39
+  onError(): void {
40
+    console.log('close connection');
41
+  },
42
+});
43
+
44
+client.enableLogger = true;

+ 78
- 7
src/client.ts View File

3
 import { ReadyStateCallback } from './types/callback';
3
 import { ReadyStateCallback } from './types/callback';
4
 import { WebsocketError } from './error';
4
 import { WebsocketError } from './error';
5
 
5
 
6
+const clientError = 400;
7
+
6
 /**
8
 /**
7
  * 初始化链接以及收发数据
9
  * 初始化链接以及收发数据
8
  */
10
  */
16
   private reconnectLock: boolean;
18
   private reconnectLock: boolean;
17
   private socket: WebSocket;
19
   private socket: WebSocket;
18
   private readyStateCallback: ReadyStateCallback;
20
   private readyStateCallback: ReadyStateCallback;
21
+  private _enableLogger: boolean;
19
 
22
 
20
   /**
23
   /**
21
    * 构造函数,初始化客户端链接
24
    * 构造函数,初始化客户端链接
30
     this.url = url;
33
     this.url = url;
31
     this.reconnectTimes = 0;
34
     this.reconnectTimes = 0;
32
     this.readyStateCallback = readyStateCallback;
35
     this.readyStateCallback = readyStateCallback;
36
+    this._enableLogger = false;
33
     this.socket = this.connect();
37
     this.socket = this.connect();
34
   }
38
   }
35
 
39
 
40
+  /**
41
+   * 设置是否允许显示运行日志
42
+   */
43
+  public set enableLogger(enableLogger: boolean) {
44
+    this._enableLogger = enableLogger;
45
+  }
46
+
47
+  /**
48
+   * 获取是否显示日志的配置信息
49
+   */
50
+  public get enableLogger(): boolean {
51
+    return this._enableLogger;
52
+  }
53
+
36
   /**
54
   /**
37
    * 发送ping请求,来保持长连接
55
    * 发送ping请求,来保持长连接
38
    * @param param 请求参数,比如{"hello":"world"}
56
    * @param param 请求参数,比如{"hello":"world"}
44
         reject: (err: WebsocketError) => void,
62
         reject: (err: WebsocketError) => void,
45
       ): void => {
63
       ): void => {
46
         if (this.socket.readyState !== this.socket.OPEN) {
64
         if (this.socket.readyState !== this.socket.OPEN) {
47
-          reject(new WebsocketError(400, 'asyncSend: connection refuse'));
65
+          if (this._enableLogger) {
66
+            console.log('[ping]: connection refuse');
67
+          }
68
+
69
+          reject(new WebsocketError(clientError, 'connection refuse'));
48
         }
70
         }
49
 
71
 
50
         const heartbeatOperator = 0;
72
         const heartbeatOperator = 0;
71
             JSON.stringify(param),
93
             JSON.stringify(param),
72
           ),
94
           ),
73
         );
95
         );
96
+
97
+        if (this._enableLogger) {
98
+          console.info(
99
+            '[send data packet]',
100
+            heartbeatOperator,
101
+            0,
102
+            this.requestHeader,
103
+            param,
104
+          );
105
+        }
74
       },
106
       },
75
     );
107
     );
76
   }
108
   }
88
         reject: (err: WebsocketError) => void,
120
         reject: (err: WebsocketError) => void,
89
       ): void => {
121
       ): void => {
90
         if (this.socket.readyState !== this.socket.OPEN) {
122
         if (this.socket.readyState !== this.socket.OPEN) {
91
-          reject(new WebsocketError(400, 'asyncSend: connection refuse'));
123
+          if (this._enableLogger) {
124
+            console.log('[ping]: connection refuse');
125
+          }
126
+
127
+          reject(
128
+            new WebsocketError(clientError, 'asyncSend: connection refuse'),
129
+          );
92
         }
130
         }
93
 
131
 
94
         const sequence = new Date().getTime();
132
         const sequence = new Date().getTime();
117
             JSON.stringify(param),
155
             JSON.stringify(param),
118
           ),
156
           ),
119
         );
157
         );
158
+
159
+        if (this._enableLogger) {
160
+          console.info(
161
+            '[send data packet]',
162
+            operator,
163
+            sequence,
164
+            this.requestHeader,
165
+            param,
166
+          );
167
+        }
120
       },
168
       },
121
     );
169
     );
122
   }
170
   }
245
     ws.binaryType = 'blob';
293
     ws.binaryType = 'blob';
246
 
294
 
247
     ws.onopen = (ev): void => {
295
     ws.onopen = (ev): void => {
296
+      if (this._enableLogger) {
297
+        console.info('[websocket] open connection');
298
+      }
299
+
248
       this.reconnectTimes = 0;
300
       this.reconnectTimes = 0;
249
 
301
 
250
       readyStateCallback.onOpen(ev);
302
       readyStateCallback.onOpen(ev);
251
     };
303
     };
252
 
304
 
253
     ws.onclose = (ev): void => {
305
     ws.onclose = (ev): void => {
306
+      if (this._enableLogger) {
307
+        console.info('[websocket] close connection');
308
+      }
309
+
254
       this.reconnect();
310
       this.reconnect();
255
 
311
 
256
       readyStateCallback.onClose(ev);
312
       readyStateCallback.onClose(ev);
257
     };
313
     };
258
 
314
 
259
     ws.onerror = (ev): void => {
315
     ws.onerror = (ev): void => {
316
+      if (this._enableLogger) {
317
+        console.info('[websocket] error');
318
+      }
319
+
260
       this.reconnect();
320
       this.reconnect();
261
 
321
 
262
       readyStateCallback.onError(ev);
322
       readyStateCallback.onError(ev);
287
               );
347
               );
288
             }
348
             }
289
 
349
 
290
-            if (operator !== 0 && packet.body !== 'null') {
291
-              console.info('receive data', packet.body);
350
+            if (this._enableLogger) {
351
+              if (operator !== 0 && packet.body !== 'null') {
352
+                console.info('receive data packet', packet.body);
353
+              }
292
             }
354
             }
293
           } catch (e) {
355
           } catch (e) {
294
             throw new Error(e);
356
             throw new Error(e);
308
   private reconnect(): void {
370
   private reconnect(): void {
309
     if (!this.reconnectLock) {
371
     if (!this.reconnectLock) {
310
       this.reconnectLock = true;
372
       this.reconnectLock = true;
311
-      console.info('websocket reconnect in ' + this.reconnectTimes + 's');
373
+      if (this._enableLogger) {
374
+        console.info('websocket reconnect in ' + this.reconnectTimes + 's');
375
+      }
376
+
312
       // 尝试重连
377
       // 尝试重连
313
       setTimeout((): void => {
378
       setTimeout((): void => {
314
         this.reconnectTimes++;
379
         this.reconnectTimes++;
324
    */
389
    */
325
   private send(data: ArrayBuffer): void {
390
   private send(data: ArrayBuffer): void {
326
     if (this.socket.readyState !== this.socket.OPEN) {
391
     if (this.socket.readyState !== this.socket.OPEN) {
327
-      console.error('WebSocket is already in CLOSING or CLOSED state.');
392
+      if (this._enableLogger) {
393
+        console.error(
394
+          '[send] WebSocket is already in CLOSING or CLOSED state.',
395
+        );
396
+      }
397
+
328
       return;
398
       return;
329
     }
399
     }
400
+
330
     try {
401
     try {
331
       this.socket.send(data);
402
       this.socket.send(data);
332
     } catch (e) {
403
     } catch (e) {
333
-      console.log('send data error', e);
404
+      throw new Error('send data error' + e);
334
     }
405
     }
335
   }
406
   }
336
 }
407
 }