Browse Source

fix listeners

Paul 5 years ago
parent
commit
9781c6edf6
2 changed files with 52 additions and 42 deletions
  1. 20
    3
      src/example/main.ts
  2. 32
    39
      src/index.ts

+ 20
- 3
src/example/main.ts View File

5
   url,
5
   url,
6
   new (class {
6
   new (class {
7
     onOpen(ev: Event) {
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
     onClose(ev: Event) {
30
     onClose(ev: Event) {
18
     }
37
     }
19
   })(),
38
   })(),
20
 );
39
 );
21
-
22
-console.log(client);

+ 32
- 39
src/index.ts View File

8
  * Client ws client, 单例模式, 负责维护连接
8
  * Client ws client, 单例模式, 负责维护连接
9
  */
9
  */
10
 class Client {
10
 class Client {
11
+  private listeners: Map<number, (data: string) => void>;
11
   private requestCallback: RequestCallback;
12
   private requestCallback: RequestCallback;
12
   private requestHeader: string;
13
   private requestHeader: string;
13
   private responseHeader: string;
14
   private responseHeader: string;
19
   private readyStateCallback: ReadyStateCallback;
20
   private readyStateCallback: ReadyStateCallback;
20
 
21
 
21
   constructor(url: string, readyStateCallback: ReadyStateCallback) {
22
   constructor(url: string, readyStateCallback: ReadyStateCallback) {
23
+    this.listeners = new Map<number, (data: string) => void>();
22
     this.maxPayload = MAX_PAYLOAD;
24
     this.maxPayload = MAX_PAYLOAD;
23
     this.url = url;
25
     this.url = url;
24
     this.readyStateCallback = readyStateCallback;
26
     this.readyStateCallback = readyStateCallback;
32
       throw new Error('asyncSend: connection refuse');
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
           requestCallback.onError(Number(code), message);
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
     const p = new Packet();
52
     const p = new Packet();
50
     this.send(p.pack(0, 0, this.requestHeader, JSON.stringify(param)));
53
     this.send(p.pack(0, 0, this.requestHeader, JSON.stringify(param)));
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
   // 获取socket的链接状态
149
   // 获取socket的链接状态
202
 
205
 
203
     ws.onopen = (ev) => {
206
     ws.onopen = (ev) => {
204
       this.reconnectTimes = 0;
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
     ws.onclose = (ev) => {
212
     ws.onclose = (ev) => {
214
       this.reconnect();
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
     ws.onerror = (ev) => {
218
     ws.onerror = (ev) => {
224
       this.reconnect();
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
     ws.onmessage = (ev) => {
224
     ws.onmessage = (ev) => {
238
           try {
229
           try {
239
             let packet = new Packet().unPack(reader.result);
230
             let packet = new Packet().unPack(reader.result);
240
             let packetLength = packet.headerLength + packet.bodyLength + 20;
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
             let operator = Number(packet.operator) + Number(packet.sequence);
236
             let operator = Number(packet.operator) + Number(packet.sequence);
246
-            if (this.requestCallback.hasOwnProperty(operator)) {
237
+            if (this.listeners.has(operator)) {
247
               if (packet.body === '') {
238
               if (packet.body === '') {
248
                 packet.body = '{}';
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
             if (operator !== 0 && packet.body !== 'null') {
247
             if (operator !== 0 && packet.body !== 'null') {
254
               console.info('receive data', packet.body);
248
               console.info('receive data', packet.body);
255
             }
249
             }
256
           } catch (e) {
250
           } catch (e) {
257
-            console.info(e);
258
             throw new Error(e);
251
             throw new Error(e);
259
           }
252
           }
260
         };
253
         };
261
       } else {
254
       } else {
262
-        throw new Error('websocket unsupported data format');
255
+        throw new Error('unsupported data format');
263
       }
256
       }
264
     };
257
     };
265
 
258