Paul пре 5 година
родитељ
комит
886f432be0

+ 1
- 0
.gitignore Прегледај датотеку

@@ -1 +1,2 @@
1 1
 node_modules
2
+dist

+ 30
- 0
.vscode/launch.json Прегледај датотеку

@@ -0,0 +1,30 @@
1
+{
2
+    // Use IntelliSense to learn about possible attributes.
3
+    // Hover to view descriptions of existing attributes.
4
+    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+    "version": "0.2.0",
6
+    "configurations": [
7
+        {
8
+            "type": "node",
9
+            "name": "vscode-jest-tests",
10
+            "request": "launch",
11
+            "args": [
12
+                "--runInBand"
13
+            ],
14
+            "cwd": "${workspaceFolder}",
15
+            "console": "integratedTerminal",
16
+            "internalConsoleOptions": "neverOpen",
17
+            "program": "${workspaceFolder}/node_modules/jest/bin/jest"
18
+        },
19
+        {
20
+            "type": "node",
21
+            "request": "launch",
22
+            "name": "Launch Program",
23
+            "program": "${workspaceFolder}/index.js",
24
+            "preLaunchTask": "tsc: build - tsconfig.json",
25
+            "outFiles": [
26
+                "${workspaceFolder}/dist/**/*.js"
27
+            ]
28
+        }
29
+    ]
30
+}

+ 15
- 0
.vscode/tasks.json Прегледај датотеку

@@ -0,0 +1,15 @@
1
+{
2
+    // See https://go.microsoft.com/fwlink/?LinkId=733558
3
+    // for the documentation about the tasks.json format
4
+    "version": "2.0.0",
5
+    "tasks": [
6
+        {
7
+            "type": "typescript",
8
+            "tsconfig": "tsconfig.json",
9
+            "option": "watch",
10
+            "problemMatcher": [
11
+                "$tsc-watch"
12
+            ]
13
+        }
14
+    ]
15
+}

+ 0
- 3
dist/callback.js Прегледај датотеку

@@ -1,3 +0,0 @@
1
-"use strict";
2
-exports.__esModule = true;
3
-//# sourceMappingURL=callback.js.map

+ 0
- 1
dist/callback.js.map Прегледај датотеку

@@ -1 +0,0 @@
1
-{"version":3,"file":"callback.js","sourceRoot":"","sources":["../src/callback.ts"],"names":[],"mappings":""}

+ 0
- 7
dist/constant.js Прегледај датотеку

@@ -1,7 +0,0 @@
1
-"use strict";
2
-exports.__esModule = true;
3
-// 单个数据包能够传输的最大数据量
4
-exports.MAX_PAYLOAD = 1024 * 1024;
5
-// 版本
6
-exports.VERSION = '1.0';
7
-//# sourceMappingURL=constant.js.map

+ 0
- 1
dist/constant.js.map Прегледај датотеку

@@ -1 +0,0 @@
1
-{"version":3,"file":"constant.js","sourceRoot":"","sources":["../src/constant.ts"],"names":[],"mappings":";;AAAA,kBAAkB;AACL,QAAA,WAAW,GAAG,IAAI,GAAG,IAAI,CAAC;AAEvC,KAAK;AACQ,QAAA,OAAO,GAAG,KAAK,CAAC"}

+ 0
- 284
dist/index.js Прегледај датотеку

@@ -1,284 +0,0 @@
1
-"use strict";
2
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
-    return new (P || (P = Promise))(function (resolve, reject) {
4
-        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
-        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
-        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
8
-    });
9
-};
10
-var __generator = (this && this.__generator) || function (thisArg, body) {
11
-    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12
-    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
-    function verb(n) { return function (v) { return step([n, v]); }; }
14
-    function step(op) {
15
-        if (f) throw new TypeError("Generator is already executing.");
16
-        while (_) try {
17
-            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18
-            if (y = 0, t) op = [op[0] & 2, t.value];
19
-            switch (op[0]) {
20
-                case 0: case 1: t = op; break;
21
-                case 4: _.label++; return { value: op[1], done: false };
22
-                case 5: _.label++; y = op[1]; op = [0]; continue;
23
-                case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
-                default:
25
-                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
-                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
-                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
-                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
-                    if (t[2]) _.ops.pop();
30
-                    _.trys.pop(); continue;
31
-            }
32
-            op = body.call(thisArg, _);
33
-        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
-        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
-    }
36
-};
37
-exports.__esModule = true;
38
-var constant = require("./constant");
39
-var packet_1 = require("./packet");
40
-var utils_1 = require("./utils");
41
-/**
42
- * Client ws client, 单例模式, 负责维护连接
43
- */
44
-var Client = /** @class */ (function () {
45
-    function Client(url, readyStateCallback) {
46
-        if (!('WebSocket' in window)) {
47
-            return;
48
-        }
49
-        this.requestHeader = '';
50
-        this.maxPayload = constant.MAX_PAYLOAD;
51
-        this.url = url;
52
-        this.readyStateCallback = readyStateCallback;
53
-        this.reconnectTimes = 0;
54
-        this.reconnectLock = false;
55
-        this.socket = this.connect();
56
-    }
57
-    // 向服务端发送ping包保持长连接
58
-    Client.prototype.ping = function (param, callback) {
59
-        if (param === void 0) { param = {}; }
60
-        if (callback === void 0) { callback = {}; }
61
-        if (typeof callback !== 'object') {
62
-            throw new Error('callback must be an object');
63
-        }
64
-        if (this.socket.readyState !== this.socket.OPEN) {
65
-            throw new Error('asyncSend: connection refuse');
66
-        }
67
-        var _this = this;
68
-        this.addMessageListener(0, function (data) {
69
-            var code = _this.getResponseProperty('code');
70
-            if (typeof code !== 'undefined') {
71
-                var message = _this.getResponseProperty('message');
72
-                if (this.callback.onError !== null) {
73
-                    this.callback.onError(code, message);
74
-                }
75
-            }
76
-            else {
77
-                this.callback.onSuccess(data);
78
-            }
79
-            this.callback.onEnd();
80
-        });
81
-        var p = new packet_1.Packet();
82
-        _this.send(p.pack(0, 0, _this.requestHeader, JSON.stringify(param)));
83
-    };
84
-    Client.prototype.send = function (data) {
85
-        if (this.socket.readyState !== this.socket.OPEN) {
86
-            console.error('WebSocket is already in CLOSING or CLOSED state.');
87
-            return;
88
-        }
89
-        try {
90
-            this.socket.send(data);
91
-        }
92
-        catch (e) {
93
-            console.log('send data error', e);
94
-        }
95
-    };
96
-    /**
97
-     * asyncSend
98
-     * @param {*} operator
99
-     * @param {*} param
100
-     * @param {*} callback 仅此次有效的callback
101
-     */
102
-    Client.prototype.asyncSend = function (operator, param, callback) {
103
-        console.info('websocket send data', operator, this.requestHeader, param);
104
-        if (typeof callback !== 'object') {
105
-            throw new Error('callback must be an object');
106
-        }
107
-        if (this.socket.readyState !== this.socket.OPEN) {
108
-            throw new Error('asyncSend: connection refuse');
109
-        }
110
-        if (callback.hasOwnProperty('onStart') &&
111
-            typeof callback.onStart === 'function') {
112
-            callback.onStart();
113
-        }
114
-        var _this = this;
115
-        var sequence = new Date().getTime();
116
-        var listener = utils_1.Utils.crc32(operator) + sequence;
117
-        this.callback[listener] = function (data) {
118
-            var code = _this.getResponseProperty('code');
119
-            if (typeof code !== 'undefined') {
120
-                var message = _this.getResponseProperty('message');
121
-                if (callback.hasOwnProperty('onError') &&
122
-                    typeof callback.onError === 'function') {
123
-                    callback.onError(code, message);
124
-                }
125
-            }
126
-            else {
127
-                if (callback.hasOwnProperty('onSuccess') &&
128
-                    typeof callback.onSuccess === 'function') {
129
-                    callback.onSuccess(data);
130
-                }
131
-            }
132
-            if (callback.hasOwnProperty('onEnd') &&
133
-                typeof callback.onEnd === 'function') {
134
-                callback.onEnd();
135
-            }
136
-            delete _this.callback[listener];
137
-        };
138
-        var p = new packet_1.Packet();
139
-        this.send(p.pack(utils_1.Utils.crc32(operator), sequence, this.requestHeader, JSON.stringify(param)));
140
-    };
141
-    // 同步请求服务端数据
142
-    Client.prototype.syncSend = function (operator, param, callback) {
143
-        return __awaiter(this, void 0, void 0, function () {
144
-            return __generator(this, function (_a) {
145
-                switch (_a.label) {
146
-                    case 0: return [4 /*yield*/, this.asyncSend(operator, param, callback)];
147
-                    case 1:
148
-                        _a.sent();
149
-                        return [2 /*return*/];
150
-                }
151
-            });
152
-        });
153
-    };
154
-    // 添加消息监听
155
-    Client.prototype.addMessageListener = function (operator, listener) {
156
-        this.callback[utils_1.Utils.crc32(operator)] = listener;
157
-    };
158
-    // 移除消息监听
159
-    Client.prototype.removeMessageListener = function (operator) {
160
-        delete this.callback[utils_1.Utils.crc32(operator)];
161
-    };
162
-    // 获取socket的链接状态
163
-    Client.prototype.getReadyState = function () {
164
-        return this.socket.readyState;
165
-    };
166
-    // 设置单个请求能够处理的最大字节数
167
-    Client.prototype.setMaxPayload = function (maxPayload) {
168
-        this.maxPayload = maxPayload;
169
-    };
170
-    // 设置请求属性
171
-    Client.prototype.setRequestProperty = function (key, value) {
172
-        var v = this.getRequestProperty(key);
173
-        this.requestHeader = this.requestHeader.replace(key + '=' + v + ';', '');
174
-        this.requestHeader = this.requestHeader + key + '=' + value + ';';
175
-    };
176
-    // 获取请求属性
177
-    Client.prototype.getRequestProperty = function (key) {
178
-        var values = this.requestHeader.split(';');
179
-        for (var index in values) {
180
-            var kv = values[index].split('=');
181
-            if (kv[0] === key) {
182
-                return kv[1];
183
-            }
184
-        }
185
-    };
186
-    // 设置Response属性
187
-    Client.prototype.setResponseProperty = function (key, value) {
188
-        var v = this.getResponseProperty(key);
189
-        this.responseHeader = this.responseHeader.replace(key + '=' + v + ';', '');
190
-        this.responseHeader = this.responseHeader + key + '=' + value + ';';
191
-    };
192
-    // 获取响应属性
193
-    Client.prototype.getResponseProperty = function (key) {
194
-        var values = this.responseHeader.split(';');
195
-        for (var index in values) {
196
-            var kv = values[index].split('=');
197
-            if (kv[0] === key) {
198
-                return kv[1];
199
-            }
200
-        }
201
-    };
202
-    // 创建连接
203
-    Client.prototype.connect = function () {
204
-        var url = this.url;
205
-        var readyStateCallback = this.readyStateCallback;
206
-        var ws = new WebSocket(url);
207
-        var _this = this;
208
-        ws.binaryType = 'blob';
209
-        ws.onopen = function (ev) {
210
-            console.info('websocket connected');
211
-            _this.reconnectTimes = 0;
212
-            if (readyStateCallback.hasOwnProperty('onopen') &&
213
-                typeof readyStateCallback.onopen === 'function') {
214
-                readyStateCallback.onopen(ev);
215
-            }
216
-        };
217
-        ws.onclose = function (ev) {
218
-            console.info('websocket disconnected');
219
-            _this.reconnect();
220
-            if (readyStateCallback.hasOwnProperty('onclose') &&
221
-                typeof readyStateCallback.onclose === 'function') {
222
-                readyStateCallback.onclose(ev);
223
-            }
224
-        };
225
-        ws.onerror = function (ev) {
226
-            console.info('websocket error disconnected');
227
-            _this.reconnect();
228
-            if (readyStateCallback.hasOwnProperty('onerror') &&
229
-                typeof readyStateCallback.onerror === 'function') {
230
-                readyStateCallback.onerror(ev);
231
-            }
232
-        };
233
-        ws.onmessage = function (ev) {
234
-            if (ev.data instanceof Blob) {
235
-                var reader = new FileReader();
236
-                reader.readAsArrayBuffer(ev.data);
237
-                reader.onload = function () {
238
-                    try {
239
-                        var packet = new packet_1.Packet().unPack(this.result);
240
-                        var packetLength = packet.headerLength + packet.bodyLength + 20;
241
-                        if (packetLength > constant.MAX_PAYLOAD) {
242
-                            throw new Error('the packet is big than ' + constant.MAX_PAYLOAD);
243
-                        }
244
-                        var operator = Number(packet.operator) + Number(packet.sequence);
245
-                        if (_this.callback.hasOwnProperty(operator)) {
246
-                            if (packet.body === '') {
247
-                                packet.body = '{}';
248
-                            }
249
-                            _this.responseHeader = packet.header;
250
-                            _this.callback[operator](JSON.parse(packet.body));
251
-                        }
252
-                        if (operator !== 0 && packet.body !== 'null') {
253
-                            console.info('receive data', packet.body);
254
-                        }
255
-                    }
256
-                    catch (e) {
257
-                        console.info(e);
258
-                        throw new Error(e);
259
-                    }
260
-                };
261
-            }
262
-            else {
263
-                throw new Error('websocket unsupported data format');
264
-            }
265
-        };
266
-        return ws;
267
-    };
268
-    Client.prototype.reconnect = function () {
269
-        var _this_1 = this;
270
-        if (!this.reconnectLock) {
271
-            this.reconnectLock = true;
272
-            console.info('websocket reconnect in ' + this.reconnectTimes + 's');
273
-            // 尝试重连
274
-            setTimeout(function () {
275
-                _this_1.reconnectTimes++;
276
-                _this_1.socket = _this_1.connect();
277
-                _this_1.reconnectLock = false;
278
-            }, this.reconnectTimes * 1000);
279
-        }
280
-    };
281
-    return Client;
282
-}());
283
-exports.Client = Client;
284
-//# sourceMappingURL=index.js.map

+ 0
- 1
dist/index.js.map
Разлика између датотеке није приказан због своје велике величине
Прегледај датотеку


+ 0
- 47
dist/packet.js Прегледај датотеку

@@ -1,47 +0,0 @@
1
-"use strict";
2
-exports.__esModule = true;
3
-var utils_1 = require("./utils");
4
-var Int64 = require("node-int64");
5
-var Packet = /** @class */ (function () {
6
-    function Packet() {
7
-        this.key = 'b8ca9aa66def05ff3f24919274bb4a66';
8
-    }
9
-    Packet.prototype.pack = function (operator, sequence, header, body) {
10
-        header = utils_1.Utils.encrypt(header, this.key, this.key);
11
-        body = utils_1.Utils.encrypt(body, this.key, this.key);
12
-        var headerLength = header.length;
13
-        var bodyLength = body.length;
14
-        var buf = new ArrayBuffer(20 + headerLength + bodyLength);
15
-        var dataView = new DataView(buf);
16
-        var nsBuf = new Int64(sequence).toBuffer();
17
-        dataView.setUint32(0, operator);
18
-        dataView.setUint32(12, headerLength);
19
-        dataView.setUint32(16, bodyLength);
20
-        var bufView = new Uint8Array(buf);
21
-        for (var i = 0; i < 8; i++) {
22
-            bufView[4 + i] = nsBuf[i];
23
-        }
24
-        for (var i_1 = 0; i_1 < headerLength; i_1++) {
25
-            bufView[20 + i_1] = header.charCodeAt(i_1);
26
-        }
27
-        for (var i_2 = 0; i_2 < bodyLength; i_2++) {
28
-            bufView[20 + headerLength + i_2] = body.charCodeAt(i_2);
29
-        }
30
-        return buf;
31
-    };
32
-    Packet.prototype.unPack = function (data) {
33
-        var dataView = new DataView(data);
34
-        this.operator = dataView.getUint32(0, false);
35
-        this.sequence = new Int64(new Uint8Array(dataView.buffer.slice(4, 12))).toNumber();
36
-        this.headerLength = dataView.getUint32(12, false);
37
-        this.bodyLength = dataView.getUint32(16, false);
38
-        var header = utils_1.Utils.ab2str(dataView.buffer.slice(20, 20 + this.headerLength));
39
-        var body = utils_1.Utils.ab2str(dataView.buffer.slice(20 + this.headerLength));
40
-        this.header = utils_1.Utils.decrypt(header, this.key, this.key);
41
-        this.body = utils_1.Utils.decrypt(body, this.key, this.key);
42
-        return this;
43
-    };
44
-    return Packet;
45
-}());
46
-exports.Packet = Packet;
47
-//# sourceMappingURL=packet.js.map

+ 0
- 1
dist/packet.js.map Прегледај датотеку

@@ -1 +0,0 @@
1
-{"version":3,"file":"packet.js","sourceRoot":"","sources":["../src/packet.ts"],"names":[],"mappings":"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"}

+ 0
- 11
dist/types/callback.d.ts Прегледај датотеку

@@ -1,11 +0,0 @@
1
-export interface readyStateCallback {
2
-    onopen(ev: Event): any;
3
-    onerror(ev: Event): any;
4
-    onclose(ev: Event): any;
5
-}
6
-export interface callback {
7
-    onStart(): any;
8
-    onSuccess(data: string): any;
9
-    onError(code: number, message: string): any;
10
-    onEnd(): any;
11
-}

+ 0
- 2
dist/types/constant.d.ts Прегледај датотеку

@@ -1,2 +0,0 @@
1
-export declare const MAX_PAYLOAD: number;
2
-export declare const VERSION = "1.0";

+ 0
- 36
dist/types/index.d.ts Прегледај датотеку

@@ -1,36 +0,0 @@
1
-import { readyStateCallback, callback } from './callback';
2
-/**
3
- * Client ws client, 单例模式, 负责维护连接
4
- */
5
-export declare class Client {
6
-    callback: callback;
7
-    requestHeader: string;
8
-    responseHeader: string;
9
-    maxPayload: number;
10
-    url: string;
11
-    reconnectTimes: number;
12
-    reconnectLock: boolean;
13
-    socket: WebSocket;
14
-    readyStateCallback: readyStateCallback;
15
-    constructor(url: string, readyStateCallback: readyStateCallback);
16
-    ping(param?: {}, callback?: {}): void;
17
-    send(data: any): void;
18
-    /**
19
-     * asyncSend
20
-     * @param {*} operator
21
-     * @param {*} param
22
-     * @param {*} callback 仅此次有效的callback
23
-     */
24
-    asyncSend(operator: any, param: any, callback: any): void;
25
-    syncSend(operator: any, param: any, callback: any): Promise<void>;
26
-    addMessageListener(operator: any, listener: any): void;
27
-    removeMessageListener(operator: any): void;
28
-    getReadyState(): number;
29
-    setMaxPayload(maxPayload: any): void;
30
-    setRequestProperty(key: any, value: any): void;
31
-    getRequestProperty(key: any): string;
32
-    setResponseProperty(key: any, value: any): void;
33
-    getResponseProperty(key: any): string;
34
-    connect(): WebSocket;
35
-    reconnect(): void;
36
-}

+ 0
- 11
dist/types/packet.d.ts Прегледај датотеку

@@ -1,11 +0,0 @@
1
-export declare class Packet {
2
-    private key;
3
-    operator: number;
4
-    sequence: number;
5
-    headerLength: number;
6
-    bodyLength: number;
7
-    header: string;
8
-    body: string;
9
-    pack(operator: number, sequence: number, header: string, body: string): ArrayBuffer;
10
-    unPack(data: any): Packet;
11
-}

+ 0
- 19
dist/types/utils.d.ts Прегледај датотеку

@@ -1,19 +0,0 @@
1
-declare global {
2
-    interface Window {
3
-        crcTable: number[];
4
-    }
5
-}
6
-declare class Utils {
7
-    private static code;
8
-    static crc32(str: string): number;
9
-    static ab2str(buf: ArrayBuffer): string;
10
-    static str2ab(str: string): ArrayBuffer;
11
-    static decrypt(data: string, key: string, iv: string): string;
12
-    static encrypt(data: string, key: string, iv: string): string;
13
-    static binToBase64(bitString: string): string;
14
-    static base64ToBin(str: string): string;
15
-    static stringToBin(str: string): string;
16
-    static binToString(bin: string): string;
17
-    private static makeCRCTable;
18
-}
19
-export { Utils };

+ 0
- 123
dist/utils.js Прегледај датотеку

@@ -1,123 +0,0 @@
1
-"use strict";
2
-exports.__esModule = true;
3
-var crypto_js_1 = require("crypto-js");
4
-var Utils = /** @class */ (function () {
5
-    function Utils() {
6
-    }
7
-    Utils.crc32 = function (str) {
8
-        var crcTable = window.crcTable || (window.crcTable = Utils.makeCRCTable());
9
-        var crc = 0 ^ -1;
10
-        for (var i = 0; i < str.length; i++) {
11
-            crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xff];
12
-        }
13
-        return (crc ^ -1) >>> 0;
14
-    };
15
-    // ArrayBuffer 转为字符串,参数为 ArrayBuffer 对象
16
-    Utils.ab2str = function (buf) {
17
-        // 注意,如果是大型二进制数组,为了避免溢出,必须一个一个字符地转
18
-        if (buf && buf.byteLength < 1024) {
19
-            return String.fromCharCode.apply(null, new Uint8Array(buf));
20
-        }
21
-        var bufView = new Uint8Array(buf);
22
-        var len = bufView.length;
23
-        var byteStr = new Array(len);
24
-        for (var i = 0; i < len; i++) {
25
-            byteStr[i] = String.fromCharCode.call(null, bufView[i]);
26
-        }
27
-        return byteStr.join('');
28
-    };
29
-    // 字符串转为 ArrayBuffer 对象,参数为字符串
30
-    Utils.str2ab = function (str) {
31
-        var buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
32
-        var bufView = new Uint8Array(buf);
33
-        for (var i = 0, strLen = str.length; i < strLen; i++) {
34
-            bufView[i] = str.charCodeAt(i);
35
-        }
36
-        return buf;
37
-    };
38
-    // 解密服务端传递过来的字符串
39
-    Utils.decrypt = function (data, key, iv) {
40
-        var binData = Utils.stringToBin(data);
41
-        var base64Data = Utils.binToBase64(binData);
42
-        var bytes = crypto_js_1.AES.decrypt(base64Data, crypto_js_1.enc.Latin1.parse(key), {
43
-            iv: crypto_js_1.enc.Latin1.parse(iv),
44
-            mode: crypto_js_1.mode.CBC,
45
-            padding: crypto_js_1.pad.Pkcs7
46
-        });
47
-        return bytes.toString(crypto_js_1.enc.Utf8);
48
-    };
49
-    // 加密字符串以后传递到服务端
50
-    Utils.encrypt = function (data, key, iv) {
51
-        var result = crypto_js_1.AES.encrypt(data, crypto_js_1.enc.Latin1.parse(key), {
52
-            iv: crypto_js_1.enc.Latin1.parse(iv),
53
-            mode: crypto_js_1.mode.CBC,
54
-            padding: crypto_js_1.pad.Pkcs7
55
-        });
56
-        return Utils.binToString(Utils.base64ToBin(result.toString()));
57
-    };
58
-    // 字节数组转换为base64编码
59
-    Utils.binToBase64 = function (bitString) {
60
-        var result = '';
61
-        var tail = bitString.length % 6;
62
-        var bitStringTemp1 = bitString.substr(0, bitString.length - tail);
63
-        var bitStringTemp2 = bitString.substr(bitString.length - tail, tail);
64
-        for (var i = 0; i < bitStringTemp1.length; i += 6) {
65
-            var index = parseInt(bitStringTemp1.substr(i, 6), 2);
66
-            result += Utils.code[index];
67
-        }
68
-        bitStringTemp2 += new Array(7 - tail).join('0');
69
-        if (tail) {
70
-            result += Utils.code[parseInt(bitStringTemp2, 2)];
71
-            result += new Array((6 - tail) / 2 + 1).join('=');
72
-        }
73
-        return result;
74
-    };
75
-    // base64编码转换为字节数组
76
-    Utils.base64ToBin = function (str) {
77
-        var bitString = '';
78
-        var tail = 0;
79
-        for (var i = 0; i < str.length; i++) {
80
-            if (str[i] !== '=') {
81
-                var decode = this.code.indexOf(str[i]).toString(2);
82
-                bitString += new Array(7 - decode.length).join('0') + decode;
83
-            }
84
-            else {
85
-                tail++;
86
-            }
87
-        }
88
-        return bitString.substr(0, bitString.length - tail * 2);
89
-    };
90
-    // 字符串转换为字节数组
91
-    Utils.stringToBin = function (str) {
92
-        var result = '';
93
-        for (var i = 0; i < str.length; i++) {
94
-            var charCode = str.charCodeAt(i).toString(2);
95
-            result += new Array(9 - charCode.length).join('0') + charCode;
96
-        }
97
-        return result;
98
-    };
99
-    // 字节数组转化为字符串
100
-    Utils.binToString = function (bin) {
101
-        var result = '';
102
-        for (var i = 0; i < bin.length; i += 8) {
103
-            result += String.fromCharCode(parseInt(bin.substr(i, 8), 2));
104
-        }
105
-        return result;
106
-    };
107
-    Utils.makeCRCTable = function () {
108
-        var c;
109
-        var crcTable = [];
110
-        for (var n = 0; n < 256; n++) {
111
-            c = n;
112
-            for (var k = 0; k < 8; k++) {
113
-                c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
114
-            }
115
-            crcTable[n] = c;
116
-        }
117
-        return crcTable;
118
-    };
119
-    Utils.code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
120
-    return Utils;
121
-}());
122
-exports.Utils = Utils;
123
-//# sourceMappingURL=utils.js.map

+ 0
- 1
dist/utils.js.map
Разлика између датотеке није приказан због своје велике величине
Прегледај датотеку


+ 7
- 0
public/index.html Прегледај датотеку

@@ -0,0 +1,7 @@
1
+<!DOCTYPE html>
2
+
3
+<htm>
4
+  <head>
5
+    <script src="../dist/example/main.js" type="text/javascript"></script>
6
+  </head>
7
+</htm>

+ 6
- 0
src/example/main.ts Прегледај датотеку

@@ -0,0 +1,6 @@
1
+import { Client } from "../index";
2
+
3
+console.log("Start")
4
+const client = new Client("ws://127.0.0.1:8081", null)
5
+
6
+console.log("client")

+ 1
- 0
tsconfig.json Прегледај датотеку

@@ -1,6 +1,7 @@
1 1
 {
2 2
   "compileOnSave": true,
3 3
   "compilerOptions": {
4
+    "module": "system",
4 5
     "alwaysStrict": true,
5 6
     "sourceMap": true,
6 7
     "declaration": true,