Browse Source

chore: update client

wxyyxc1992 5 years ago
parent
commit
6e46946cb2

packages/cts-core/example/index.ts → packages/cts-api/example/index.ts View File

1
 import { Client } from '../src/client';
1
 import { Client } from '../src/client';
2
-import { WebsocketError } from './error';
2
+import { WebsocketError } from '../src/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(url, {
5
 const client = new Client(url, {
9
       .then(
9
       .then(
10
         (res: string): void => {
10
         (res: string): void => {
11
           console.log('ping sucessful:', res);
11
           console.log('ping sucessful:', res);
12
-        },
12
+        }
13
       )
13
       )
14
       .catch(
14
       .catch(
15
         (reason: WebsocketError): void => {
15
         (reason: WebsocketError): void => {
16
           console.log('ping error:', reason.code, reason.msg);
16
           console.log('ping error:', reason.code, reason.msg);
17
-        },
17
+        }
18
       );
18
       );
19
 
19
 
20
     client
20
     client
22
       .then(
22
       .then(
23
         (res: string): void => {
23
         (res: string): void => {
24
           console.log('request successful:', res);
24
           console.log('request successful:', res);
25
-        },
25
+        }
26
       )
26
       )
27
       .catch(
27
       .catch(
28
         (reason: WebsocketError): void => {
28
         (reason: WebsocketError): void => {
29
           console.log('request error:', reason.code, reason.msg);
29
           console.log('request error:', reason.code, reason.msg);
30
-        },
30
+        }
31
       );
31
       );
32
   },
32
   },
33
 
33
 
38
 
38
 
39
   onError(): void {
39
   onError(): void {
40
     console.log('close connection');
40
     console.log('close connection');
41
-  },
41
+  }
42
 });
42
 });
43
 
43
 
44
 client.enableLogger = true;
44
 client.enableLogger = true;

packages/cts-core/example/types.d.ts → packages/cts-api/example/types.d.ts View File


packages/cts-core/package.json → packages/cts-api/package.json View File

1
 {
1
 {
2
   "author": "Chevalier",
2
   "author": "Chevalier",
3
-  "description": "cts-core",
3
+  "description": "cts-api",
4
   "license": "MIT",
4
   "license": "MIT",
5
   "keywords": [
5
   "keywords": [
6
     "webpack",
6
     "webpack",
7
     "react"
7
     "react"
8
   ],
8
   ],
9
-  "name": "cts-core",
9
+  "name": "cts-api",
10
   "version": "0.0.1-alpha.1",
10
   "version": "0.0.1-alpha.1",
11
   "repository": {
11
   "repository": {
12
     "type": "git",
12
     "type": "git",

packages/cts-core/postcss.config.js → packages/cts-api/postcss.config.js View File


packages/cts-core/public/favicon.ico → packages/cts-api/public/favicon.ico View File


packages/cts-core/public/index.html → packages/cts-api/public/index.html View File


packages/cts-core/public/manifest.json → packages/cts-api/public/manifest.json View File


packages/cts-core/scripts/webpack/webpack.config.dev.js → packages/cts-api/scripts/webpack/webpack.config.dev.js View File


packages/cts-core/scripts/webpack/webpack.config.umd.js → packages/cts-api/scripts/webpack/webpack.config.umd.js View File


+ 1
- 0
packages/cts-api/src/WebSocketClient.ts View File

1
+export class WebSocketClient {}

packages/cts-core/src/client.ts → packages/cts-api/src/client.ts View File

72
    */
72
    */
73
   public async ping(param: object): Promise<string> {
73
   public async ping(param: object): Promise<string> {
74
     return new Promise(
74
     return new Promise(
75
-      (
76
-        resolve: (data: string) => void,
77
-        reject: (err: WebsocketError) => void,
78
-      ): void => {
75
+      (resolve: (data: string) => void, reject: (err: WebsocketError) => void): void => {
79
         if (this.socket.readyState !== this.socket.OPEN) {
76
         if (this.socket.readyState !== this.socket.OPEN) {
80
           if (this._enableLogger) {
77
           if (this._enableLogger) {
81
             console.log('[ping]: connection refuse');
78
             console.log('[ping]: connection refuse');
96
             } else {
93
             } else {
97
               resolve(data);
94
               resolve(data);
98
             }
95
             }
99
-          },
96
+          }
100
         );
97
         );
101
 
98
 
102
         const p = new Packet();
99
         const p = new Packet();
103
-        this.send(
104
-          p.pack(
105
-            heartbeatOperator,
106
-            0,
107
-            this.requestHeader,
108
-            JSON.stringify(param),
109
-          ),
110
-        );
100
+        this.send(p.pack(heartbeatOperator, 0, this.requestHeader, JSON.stringify(param)));
111
 
101
 
112
         if (this._enableLogger) {
102
         if (this._enableLogger) {
113
-          console.info(
114
-            '[send data packet]',
115
-            heartbeatOperator,
116
-            0,
117
-            this.requestHeader,
118
-            param,
119
-          );
103
+          console.info('[send data packet]', heartbeatOperator, 0, this.requestHeader, param);
120
         }
104
         }
121
-      },
105
+      }
122
     );
106
     );
123
   }
107
   }
124
 
108
 
138
    * @param operator 消息监听地址
122
    * @param operator 消息监听地址
139
    * @param listener 定义如何处理从服务端返回的消息
123
    * @param listener 定义如何处理从服务端返回的消息
140
    */
124
    */
141
-  public addMessageListener(
142
-    operator: string,
143
-    listener: (data: string) => void,
144
-  ): void {
125
+  public addMessageListener(operator: string, listener: (data: string) => void): void {
145
     this.listeners.set(Utils.crc32(operator), listener);
126
     this.listeners.set(Utils.crc32(operator), listener);
146
   }
127
   }
147
 
128
 
280
 
261
 
281
               this.responseHeader = packet.header;
262
               this.responseHeader = packet.header;
282
 
263
 
283
-              (this.listeners.get(operator) as (data: string) => void)(
284
-                JSON.parse(packet.body),
285
-              );
264
+              (this.listeners.get(operator) as (data: string) => void)(JSON.parse(packet.body));
286
             }
265
             }
287
 
266
 
288
             if (this._enableLogger) {
267
             if (this._enableLogger) {
328
   private send(data: ArrayBuffer): void {
307
   private send(data: ArrayBuffer): void {
329
     if (this.socket.readyState !== this.socket.OPEN) {
308
     if (this.socket.readyState !== this.socket.OPEN) {
330
       if (this._enableLogger) {
309
       if (this._enableLogger) {
331
-        console.error(
332
-          '[send] WebSocket is already in CLOSING or CLOSED state.',
333
-        );
310
+        console.error('[send] WebSocket is already in CLOSING or CLOSED state.');
334
       }
311
       }
335
 
312
 
336
       return;
313
       return;
351
    */
328
    */
352
   private asyncSend(operator: string, param: object): Promise<string> {
329
   private asyncSend(operator: string, param: object): Promise<string> {
353
     return new Promise(
330
     return new Promise(
354
-      (
355
-        resolve: (data: string) => void,
356
-        reject: (err: WebsocketError) => void,
357
-      ): void => {
331
+      (resolve: (data: string) => void, reject: (err: WebsocketError) => void): void => {
358
         if (this.socket.readyState !== this.socket.OPEN) {
332
         if (this.socket.readyState !== this.socket.OPEN) {
359
           if (this._enableLogger) {
333
           if (this._enableLogger) {
360
             console.log('[ping]: connection refuse');
334
             console.log('[ping]: connection refuse');
361
           }
335
           }
362
 
336
 
363
-          reject(
364
-            new WebsocketError(clientError, 'asyncSend: connection refuse'),
365
-          );
337
+          reject(new WebsocketError(clientError, 'asyncSend: connection refuse'));
366
         }
338
         }
367
 
339
 
368
         const sequence = new Date().getTime();
340
         const sequence = new Date().getTime();
379
             }
351
             }
380
 
352
 
381
             delete this.listeners[listener];
353
             delete this.listeners[listener];
382
-          },
354
+          }
383
         );
355
         );
384
 
356
 
385
         const p = new Packet();
357
         const p = new Packet();
386
         this.send(
358
         this.send(
387
-          p.pack(
388
-            Utils.crc32(operator),
389
-            sequence,
390
-            this.requestHeader,
391
-            JSON.stringify(param),
392
-          ),
359
+          p.pack(Utils.crc32(operator), sequence, this.requestHeader, JSON.stringify(param))
393
         );
360
         );
394
 
361
 
395
         if (this._enableLogger) {
362
         if (this._enableLogger) {
396
-          console.info(
397
-            '[send data packet]',
398
-            operator,
399
-            sequence,
400
-            this.requestHeader,
401
-            param,
402
-          );
363
+          console.info('[send data packet]', operator, sequence, this.requestHeader, param);
403
         }
364
         }
404
-      },
365
+      }
405
     );
366
     );
406
   }
367
   }
407
 }
368
 }

+ 2
- 0
packages/cts-api/src/config.ts View File

1
+// PING_INTERVAL 心跳包时间间隔
2
+const PING_INTERVAL = 50 * 1000;

packages/cts-core/src/error.ts → packages/cts-api/src/error.ts View File


+ 3
- 0
packages/cts-api/src/index.ts View File

1
+export { WebSocketClient } from './WebSocketClient';
2
+export { WebsocketError } from './error';
3
+export { Client } from './client';

+ 77
- 0
packages/cts-api/src/meta.ts View File

1
+export function getMetaData() {
2
+  const nAgt = navigator.userAgent;
3
+  let browserName = navigator.appName;
4
+  let fullVersion = `${parseFloat(navigator.appVersion)}`;
5
+  let majorVersion = parseInt(navigator.appVersion, 10);
6
+  let nameOffset;
7
+  let verOffset;
8
+  let ix;
9
+
10
+  // In Opera, the true version is after "Opera" or after "Version"
11
+  if ((verOffset = nAgt.indexOf('Opera')) !== -1) {
12
+    browserName = 'Opera';
13
+    fullVersion = nAgt.substring(verOffset + 6);
14
+    if ((verOffset = nAgt.indexOf('Version')) !== -1) fullVersion = nAgt.substring(verOffset + 8);
15
+  } else if ((verOffset = nAgt.indexOf('MSIE')) !== -1) {
16
+    // In MSIE, the true version is after "MSIE" in userAgent
17
+    browserName = 'Microsoft Internet Explorer';
18
+    fullVersion = nAgt.substring(verOffset + 5);
19
+  } else if ((verOffset = nAgt.indexOf('Chrome')) !== -1) {
20
+    // In Chrome, the true version is after "Chrome"
21
+    browserName = 'Chrome';
22
+    fullVersion = nAgt.substring(verOffset + 7);
23
+  } else if ((verOffset = nAgt.indexOf('Safari')) !== -1) {
24
+    // In Safari, the true version is after "Safari" or after "Version"
25
+    browserName = 'Safari';
26
+    fullVersion = nAgt.substring(verOffset + 7);
27
+    if ((verOffset = nAgt.indexOf('Version')) !== -1) fullVersion = nAgt.substring(verOffset + 8);
28
+  } else if ((verOffset = nAgt.indexOf('Firefox')) !== -1) {
29
+    // In Firefox, the true version is after "Firefox"
30
+    browserName = 'Firefox';
31
+    fullVersion = nAgt.substring(verOffset + 8);
32
+  } else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
33
+    // In most other browsers, "name/version" is at the end of userAgent
34
+    browserName = nAgt.substring(nameOffset, verOffset);
35
+    fullVersion = nAgt.substring(verOffset + 1);
36
+    if (browserName.toLowerCase() === browserName.toUpperCase()) {
37
+      browserName = navigator.appName;
38
+    }
39
+  }
40
+  // trim the fullVersion string at semicolon/space if present
41
+  if ((ix = fullVersion.indexOf(';')) !== -1) fullVersion = fullVersion.substring(0, ix);
42
+  if ((ix = fullVersion.indexOf(' ')) !== -1) fullVersion = fullVersion.substring(0, ix);
43
+
44
+  majorVersion = parseInt(`${fullVersion}`, 10);
45
+  if (isNaN(majorVersion)) {
46
+    fullVersion = `${parseFloat(navigator.appVersion)}`;
47
+    majorVersion = parseInt(navigator.appVersion, 10);
48
+  }
49
+
50
+  let OSName = 'Unknown OS';
51
+  if (navigator.appVersion.indexOf('Win') !== -1) OSName = 'Windows';
52
+  if (navigator.appVersion.indexOf('Mac') !== -1) OSName = 'MacOS';
53
+  if (navigator.appVersion.indexOf('X11') !== -1) OSName = 'UNIX';
54
+  if (navigator.appVersion.indexOf('Linux') !== -1) OSName = 'Linux';
55
+
56
+  let isMobile = false; // initiate as false
57
+  // device detection
58
+  if (
59
+    /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(
60
+      navigator.userAgent
61
+    ) ||
62
+    /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
63
+      navigator.userAgent.substr(0, 4)
64
+    )
65
+  ) {
66
+    isMobile = true;
67
+  }
68
+
69
+  return {
70
+    device: isMobile ? 'mobile' : 'pc',
71
+    os: OSName,
72
+    os_version: '',
73
+    app: 'WebLiveClient',
74
+    app_version: fullVersion,
75
+    tag: {}
76
+  };
77
+}

packages/cts-core/src/packet.ts → packages/cts-api/src/packet.ts View File


packages/cts-core/src/types/callback.ts → packages/cts-api/src/types/callback.ts View File


packages/cts-core/src/utils.ts → packages/cts-api/src/utils.ts View File


packages/cts-core/tsconfig.cjs.json → packages/cts-api/tsconfig.cjs.json View File


packages/cts-core/tsconfig.json → packages/cts-api/tsconfig.json View File


packages/cts-core/tslint.json → packages/cts-api/tslint.json View File


packages/cts-core/yarn.lock → packages/cts-api/yarn.lock View File


+ 0
- 0
packages/cts-core/src/index.ts View File


+ 0
- 14
packages/cts-core/types.d.ts View File

1
-declare module '*.less' {
2
-  const styles: Record<string, string>;
3
-  export = styles;
4
-}
5
-
6
-declare module '*.css' {
7
-  const content: any;
8
-  export default content;
9
-}
10
-
11
-declare module '*.svg' {
12
-  const content: string;
13
-  export default content;
14
-}