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,44 +2,43 @@ import { Client } from '../src/client';
2 2
 import { WebsocketError } from './error';
3 3
 
4 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,6 +3,8 @@ import { Utils } from './utils';
3 3
 import { ReadyStateCallback } from './types/callback';
4 4
 import { WebsocketError } from './error';
5 5
 
6
+const clientError = 400;
7
+
6 8
 /**
7 9
  * 初始化链接以及收发数据
8 10
  */
@@ -16,6 +18,7 @@ class Client {
16 18
   private reconnectLock: boolean;
17 19
   private socket: WebSocket;
18 20
   private readyStateCallback: ReadyStateCallback;
21
+  private _enableLogger: boolean;
19 22
 
20 23
   /**
21 24
    * 构造函数,初始化客户端链接
@@ -30,9 +33,24 @@ class Client {
30 33
     this.url = url;
31 34
     this.reconnectTimes = 0;
32 35
     this.readyStateCallback = readyStateCallback;
36
+    this._enableLogger = false;
33 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 55
    * 发送ping请求,来保持长连接
38 56
    * @param param 请求参数,比如{"hello":"world"}
@@ -44,7 +62,11 @@ class Client {
44 62
         reject: (err: WebsocketError) => void,
45 63
       ): void => {
46 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 72
         const heartbeatOperator = 0;
@@ -71,6 +93,16 @@ class Client {
71 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,7 +120,13 @@ class Client {
88 120
         reject: (err: WebsocketError) => void,
89 121
       ): void => {
90 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 132
         const sequence = new Date().getTime();
@@ -117,6 +155,16 @@ class Client {
117 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,18 +293,30 @@ class Client {
245 293
     ws.binaryType = 'blob';
246 294
 
247 295
     ws.onopen = (ev): void => {
296
+      if (this._enableLogger) {
297
+        console.info('[websocket] open connection');
298
+      }
299
+
248 300
       this.reconnectTimes = 0;
249 301
 
250 302
       readyStateCallback.onOpen(ev);
251 303
     };
252 304
 
253 305
     ws.onclose = (ev): void => {
306
+      if (this._enableLogger) {
307
+        console.info('[websocket] close connection');
308
+      }
309
+
254 310
       this.reconnect();
255 311
 
256 312
       readyStateCallback.onClose(ev);
257 313
     };
258 314
 
259 315
     ws.onerror = (ev): void => {
316
+      if (this._enableLogger) {
317
+        console.info('[websocket] error');
318
+      }
319
+
260 320
       this.reconnect();
261 321
 
262 322
       readyStateCallback.onError(ev);
@@ -287,8 +347,10 @@ class Client {
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 355
           } catch (e) {
294 356
             throw new Error(e);
@@ -308,7 +370,10 @@ class Client {
308 370
   private reconnect(): void {
309 371
     if (!this.reconnectLock) {
310 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 378
       setTimeout((): void => {
314 379
         this.reconnectTimes++;
@@ -324,13 +389,19 @@ class Client {
324 389
    */
325 390
   private send(data: ArrayBuffer): void {
326 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 398
       return;
329 399
     }
400
+
330 401
     try {
331 402
       this.socket.send(data);
332 403
     } catch (e) {
333
-      console.log('send data error', e);
404
+      throw new Error('send data error' + e);
334 405
     }
335 406
   }
336 407
 }