瀏覽代碼

fix listeners

Paul 5 年之前
父節點
當前提交
9781c6edf6
共有 2 個文件被更改,包括 52 次插入42 次删除
  1. 20
    3
      src/example/main.ts
  2. 32
    39
      src/index.ts

+ 20
- 3
src/example/main.ts 查看文件

@@ -5,7 +5,26 @@ const client = new Client(
5 5
   url,
6 6
   new (class {
7 7
     onOpen(ev: Event) {
8
-      console.log('open connection', ev.target);
8
+      client.ping(
9
+        undefined,
10
+        new (class {
11
+          onStart(): void {
12
+            console.log('start ping');
13
+          }
14
+
15
+          onSuccess(data: string): void {
16
+            console.log('ping successful:', data);
17
+          }
18
+
19
+          onError(code: number, message: string): void {
20
+            console.log('ping error:', message);
21
+          }
22
+
23
+          onEnd(): void {
24
+            console.log('end ping');
25
+          }
26
+        })(),
27
+      );
9 28
     }
10 29
 
11 30
     onClose(ev: Event) {
@@ -18,5 +37,3 @@ const client = new Client(
18 37
     }
19 38
   })(),
20 39
 );
21
-
22
-console.log(client);

+ 32
- 39
src/index.ts 查看文件

@@ -8,6 +8,7 @@ const MAX_PAYLOAD = 1024 * 1024;
8 8
  * Client ws client, 单例模式, 负责维护连接
9 9
  */
10 10
 class Client {
11
+  private listeners: Map<number, (data: string) => void>;
11 12
   private requestCallback: RequestCallback;
12 13
   private requestHeader: string;
13 14
   private responseHeader: string;
@@ -19,6 +20,7 @@ class Client {
19 20
   private readyStateCallback: ReadyStateCallback;
20 21
 
21 22
   constructor(url: string, readyStateCallback: ReadyStateCallback) {
23
+    this.listeners = new Map<number, (data: string) => void>();
22 24
     this.maxPayload = MAX_PAYLOAD;
23 25
     this.url = url;
24 26
     this.readyStateCallback = readyStateCallback;
@@ -32,19 +34,20 @@ class Client {
32 34
       throw new Error('asyncSend: connection refuse');
33 35
     }
34 36
 
35
-    this.addMessageListener(0, (data) => {
36
-      let code = this.getResponseProperty('code');
37
-      if (typeof code !== 'undefined') {
38
-        let message = this.getResponseProperty('message');
39
-        if (requestCallback.onError !== null) {
37
+    this.listeners.set(
38
+      0,
39
+      (data: string): void => {
40
+        const code = this.getResponseProperty('code');
41
+        if (code !== '') {
42
+          const message = this.getResponseProperty('message');
40 43
           requestCallback.onError(Number(code), message);
44
+        } else {
45
+          requestCallback.onSuccess(data);
41 46
         }
42
-      } else {
43
-        requestCallback.onSuccess(data);
44
-      }
45 47
 
46
-      requestCallback.onEnd();
47
-    });
48
+        requestCallback.onEnd();
49
+      },
50
+    );
48 51
 
49 52
     const p = new Packet();
50 53
     this.send(p.pack(0, 0, this.requestHeader, JSON.stringify(param)));
@@ -134,13 +137,13 @@ class Client {
134 137
   }
135 138
 
136 139
   // 添加消息监听
137
-  addMessageListener(operator, listener) {
138
-    this.requestCallback[Utils.crc32(operator)] = listener;
140
+  addMessageListener(operator: string, listener: (data: string) => void) {
141
+    this.listeners[Utils.crc32(operator)] = listener;
139 142
   }
140 143
 
141 144
   // 移除消息监听
142
-  removeMessageListener(operator) {
143
-    delete this.requestCallback[Utils.crc32(operator)];
145
+  removeMessageListener(operator: string) {
146
+    delete this.listeners[Utils.crc32(operator)];
144 147
   }
145 148
 
146 149
   // 获取socket的链接状态
@@ -202,32 +205,20 @@ class Client {
202 205
 
203 206
     ws.onopen = (ev) => {
204 207
       this.reconnectTimes = 0;
205
-      if (
206
-        readyStateCallback.hasOwnProperty('onOpen') &&
207
-        typeof readyStateCallback.onOpen === 'function'
208
-      ) {
209
-        readyStateCallback.onOpen(ev);
210
-      }
208
+
209
+      readyStateCallback.onOpen(ev);
211 210
     };
212 211
 
213 212
     ws.onclose = (ev) => {
214 213
       this.reconnect();
215
-      if (
216
-        readyStateCallback.hasOwnProperty('onClose') &&
217
-        typeof readyStateCallback.onClose === 'function'
218
-      ) {
219
-        readyStateCallback.onClose(ev);
220
-      }
214
+
215
+      readyStateCallback.onClose(ev);
221 216
     };
222 217
 
223 218
     ws.onerror = (ev) => {
224 219
       this.reconnect();
225
-      if (
226
-        readyStateCallback.hasOwnProperty('onError') &&
227
-        typeof readyStateCallback.onError === 'function'
228
-      ) {
229
-        readyStateCallback.onError(ev);
230
-      }
220
+
221
+      readyStateCallback.onError(ev);
231 222
     };
232 223
 
233 224
     ws.onmessage = (ev) => {
@@ -238,28 +229,30 @@ class Client {
238 229
           try {
239 230
             let packet = new Packet().unPack(reader.result);
240 231
             let packetLength = packet.headerLength + packet.bodyLength + 20;
241
-            if (packetLength > MAX_PAYLOAD) {
242
-              throw new Error('the packet is big than ' + MAX_PAYLOAD);
232
+            if (packetLength > this.maxPayload) {
233
+              throw new Error('the packet is big than ' + this.maxPayload);
243 234
             }
244 235
 
245 236
             let operator = Number(packet.operator) + Number(packet.sequence);
246
-            if (this.requestCallback.hasOwnProperty(operator)) {
237
+            if (this.listeners.has(operator)) {
247 238
               if (packet.body === '') {
248 239
                 packet.body = '{}';
249 240
               }
250
-              this.responseHeader = packet.header;
251
-              this.requestCallback[operator](JSON.parse(packet.body));
241
+
242
+              (<(data: string) => void>this.listeners.get(operator))(
243
+                packet.body,
244
+              );
252 245
             }
246
+
253 247
             if (operator !== 0 && packet.body !== 'null') {
254 248
               console.info('receive data', packet.body);
255 249
             }
256 250
           } catch (e) {
257
-            console.info(e);
258 251
             throw new Error(e);
259 252
           }
260 253
         };
261 254
       } else {
262
-        throw new Error('websocket unsupported data format');
255
+        throw new Error('unsupported data format');
263 256
       }
264 257
     };
265 258