Paul 5 years ago
parent
commit
b684458a83
3 changed files with 121 additions and 108 deletions
  1. 26
    42
      example/main.ts
  2. 69
    66
      src/client.ts
  3. 26
    0
      src/error.ts

+ 26
- 42
example/main.ts View File

@@ -1,52 +1,36 @@
1 1
 import { Client } from '../src/client';
2
+import { WebsocketError } from './error';
2 3
 
3 4
 const url = 'ws://127.0.0.1:8081';
4 5
 const client = new Client(
5 6
   url,
6 7
   new (class {
7 8
     public onOpen(): void {
8
-      client.ping(
9
-        {},
10
-        new (class {
11
-          public onStart(): void {
12
-            console.log('start ping');
13
-          }
14
-
15
-          public onSuccess(data: string): void {
16
-            console.log('ping successful:', data);
17
-          }
18
-
19
-          public onError(code: number, message: string): void {
20
-            console.log('ping error:', message);
21
-          }
22
-
23
-          public onEnd(): void {
24
-            console.log('end ping');
25
-          }
26
-        })(),
27
-      );
28
-
29
-      client.asyncSend(
30
-        '/v1/healthy',
31
-        {},
32
-        new (class {
33
-          public onStart(): void {
34
-            console.log('start request');
35
-          }
36
-
37
-          public onSuccess(data: string): void {
38
-            console.log('request successful:', data);
39
-          }
40
-
41
-          public onError(code: number, message: string): void {
42
-            console.log('request error:', message);
43
-          }
44
-
45
-          public onEnd(): void {
46
-            console.log('end request');
47
-          }
48
-        })(),
49
-      );
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
+        );
21
+
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
+        );
50 34
     }
51 35
 
52 36
     public onClose(ev: Event): void {

+ 69
- 66
src/client.ts View File

@@ -1,6 +1,7 @@
1 1
 import { Packet } from './packet';
2 2
 import { Utils } from './utils';
3
-import { ReadyStateCallback, RequestCallback } from './types/callback';
3
+import { ReadyStateCallback } from './types/callback';
4
+import { WebsocketError } from './error';
4 5
 
5 6
 /**
6 7
  * 初始化链接以及收发数据
@@ -35,34 +36,43 @@ class Client {
35 36
   /**
36 37
    * 发送ping请求,来保持长连接
37 38
    * @param param 请求参数,比如{"hello":"world"}
38
-   * @param requestCallback 请求状态回调
39 39
    */
40
-  public ping(param: object, requestCallback: RequestCallback): void {
41
-    if (this.socket.readyState !== this.socket.OPEN) {
42
-      throw new Error('asyncSend: connection refuse');
43
-    }
44
-
45
-    const heartbeatOperator = 0;
46
-
47
-    this.listeners.set(
48
-      heartbeatOperator,
49
-      (data: string): void => {
50
-        const code = this.getResponseProperty('code');
51
-        if (code !== '') {
52
-          const message = this.getResponseProperty('message');
53
-          requestCallback.onError(Number(code), message);
54
-        } else {
55
-          requestCallback.onSuccess(data);
40
+  public async ping(param: object): Promise<string> {
41
+    return new Promise(
42
+      (
43
+        resolve: (data: string) => void,
44
+        reject: (err: WebsocketError) => void,
45
+      ): void => {
46
+        if (this.socket.readyState !== this.socket.OPEN) {
47
+          reject(new WebsocketError(400, 'asyncSend: connection refuse'));
56 48
         }
57 49
 
58
-        requestCallback.onEnd();
50
+        const heartbeatOperator = 0;
51
+
52
+        this.listeners.set(
53
+          heartbeatOperator,
54
+          (data: string): void => {
55
+            const code = this.getResponseProperty('code');
56
+            if (code !== '') {
57
+              const message = this.getResponseProperty('message');
58
+              reject(new WebsocketError(Number(code), message));
59
+            } else {
60
+              resolve(data);
61
+            }
62
+          },
63
+        );
64
+
65
+        const p = new Packet();
66
+        this.send(
67
+          p.pack(
68
+            heartbeatOperator,
69
+            0,
70
+            this.requestHeader,
71
+            JSON.stringify(param),
72
+          ),
73
+        );
59 74
       },
60 75
     );
61
-
62
-    const p = new Packet();
63
-    this.send(
64
-      p.pack(heartbeatOperator, 0, this.requestHeader, JSON.stringify(param)),
65
-    );
66 76
   }
67 77
 
68 78
   /**
@@ -71,47 +81,44 @@ class Client {
71 81
    * @param param 请求参数,比如{"hello":"world"}
72 82
    * @param callback 请求状态回调处理
73 83
    */
74
-  public asyncSend(
75
-    operator: string,
76
-    param: object,
77
-    callback: RequestCallback,
78
-  ): void {
79
-    console.info('websocket send data', operator, this.requestHeader, param);
80
-
81
-    if (this.socket.readyState !== this.socket.OPEN) {
82
-      throw new Error('asyncSend: connection refuse');
83
-    }
84
-
85
-    callback.onStart();
86
-
87
-    const sequence = new Date().getTime();
88
-    const listener = Utils.crc32(operator) + sequence;
89
-    this.listeners.set(
90
-      listener,
91
-      (data: string): void => {
92
-        const code = this.getResponseProperty('code');
93
-        if (code !== '') {
94
-          const message = this.getResponseProperty('message');
95
-          callback.onError(Number(code), message);
96
-        } else {
97
-          callback.onSuccess(data);
84
+  private asyncSend(operator: string, param: object): Promise<string> {
85
+    return new Promise(
86
+      (
87
+        resolve: (data: string) => void,
88
+        reject: (err: WebsocketError) => void,
89
+      ): void => {
90
+        if (this.socket.readyState !== this.socket.OPEN) {
91
+          reject(new WebsocketError(400, 'asyncSend: connection refuse'));
98 92
         }
99 93
 
100
-        callback.onEnd();
94
+        const sequence = new Date().getTime();
95
+        const listener = Utils.crc32(operator) + sequence;
96
+        this.listeners.set(
97
+          listener,
98
+          (data: string): void => {
99
+            const code = this.getResponseProperty('code');
100
+            if (code !== '') {
101
+              const message = this.getResponseProperty('message');
102
+              reject(new WebsocketError(Number(code), message));
103
+            } else {
104
+              resolve(data);
105
+            }
101 106
 
102
-        delete this.listeners[listener];
107
+            delete this.listeners[listener];
108
+          },
109
+        );
110
+
111
+        const p = new Packet();
112
+        this.send(
113
+          p.pack(
114
+            Utils.crc32(operator),
115
+            sequence,
116
+            this.requestHeader,
117
+            JSON.stringify(param),
118
+          ),
119
+        );
103 120
       },
104 121
     );
105
-
106
-    const p = new Packet();
107
-    this.send(
108
-      p.pack(
109
-        Utils.crc32(operator),
110
-        sequence,
111
-        this.requestHeader,
112
-        JSON.stringify(param),
113
-      ),
114
-    );
115 122
   }
116 123
 
117 124
   /**
@@ -120,12 +127,8 @@ class Client {
120 127
    * @param param 请求参数,比如{"hello":"world"}
121 128
    * @param callback 请求状态回调处理
122 129
    */
123
-  public async syncSend(
124
-    operator: string,
125
-    param: object,
126
-    callback: RequestCallback,
127
-  ): Promise<void> {
128
-    await this.asyncSend(operator, param, callback);
130
+  public async request(operator: string, param: object): Promise<string> {
131
+    return await this.asyncSend(operator, param);
129 132
   }
130 133
 
131 134
   /**

+ 26
- 0
src/error.ts View File

@@ -0,0 +1,26 @@
1
+export class WebsocketError {
2
+  private _code: number;
3
+  private _msg: string;
4
+
5
+  /**
6
+   * 构造函数
7
+   */
8
+  public constructor(code: number, msg: string) {
9
+    this._code = code;
10
+    this._msg = msg;
11
+  }
12
+
13
+  /**
14
+   * 返回错误码
15
+   */
16
+  public get code(): number {
17
+    return this._code;
18
+  }
19
+
20
+  /**
21
+   * 返回具体的错误信息
22
+   */
23
+  public get msg(): string {
24
+    return this._msg;
25
+  }
26
+}