|
@@ -0,0 +1,447 @@
|
|
1
|
+import { Packet } from './packet';
|
|
2
|
+import { Utils } from './utils';
|
|
3
|
+import {
|
|
4
|
+ WebsocketError,
|
|
5
|
+ WebSocketResp,
|
|
6
|
+ ReadyStateCallback,
|
|
7
|
+} from './types/index';
|
|
8
|
+import EventEmitter from 'eventemitter3';
|
|
9
|
+
|
|
10
|
+const clientError = 400;
|
|
11
|
+
|
|
12
|
+/**
|
|
13
|
+ * 初始化链接以及收发数据
|
|
14
|
+ */
|
|
15
|
+class Client {
|
|
16
|
+ private _maxPayload: number;
|
|
17
|
+ private _enableLogger: boolean;
|
|
18
|
+ private static instance: Client;
|
|
19
|
+ private listeners: EventEmitter;
|
|
20
|
+ private binaryType: BinaryType;
|
|
21
|
+ private requestHeader: string;
|
|
22
|
+ private responseHeader: string;
|
|
23
|
+ private url: string;
|
|
24
|
+ private reconnectTimes: number;
|
|
25
|
+ private reconnectLock: boolean;
|
|
26
|
+ private socket: WebSocket;
|
|
27
|
+ private readyStateCallback: ReadyStateCallback;
|
|
28
|
+
|
|
29
|
+ /**
|
|
30
|
+ * 构造函数,初始化客户端链接
|
|
31
|
+ * @param url websocket链接地址
|
|
32
|
+ * @param readyStateCallback 链接状态回调,可以处理onOpen、onClose、onError
|
|
33
|
+ */
|
|
34
|
+ private constructor(url: string, readyStateCallback: ReadyStateCallback, binaryType?: BinaryType) {
|
|
35
|
+ this.binaryType = binaryType || 'blob';
|
|
36
|
+ this.listeners = new EventEmitter();
|
|
37
|
+ this.requestHeader = '';
|
|
38
|
+ this.requestHeader = '';
|
|
39
|
+ this._maxPayload = 1024 * 1024;
|
|
40
|
+ this.url = url;
|
|
41
|
+ this.reconnectTimes = 0;
|
|
42
|
+ this.readyStateCallback = readyStateCallback;
|
|
43
|
+ this._enableLogger = false;
|
|
44
|
+ this.socket = this.connect();
|
|
45
|
+ }
|
|
46
|
+
|
|
47
|
+ /**
|
|
48
|
+ * 通过单例模式获取客户端链接
|
|
49
|
+ * @param url websocket链接地址
|
|
50
|
+ * @param readyStateCallback 链接状态回调,可以处理onOpen、onClose、onError
|
|
51
|
+ * @param binaryType "arraybuffer" | "blob"
|
|
52
|
+ * @param allwaysNew 是否保持新建Client
|
|
53
|
+ */
|
|
54
|
+ public static getInstance(url: string, callback: ReadyStateCallback, binaryType?: BinaryType, allwaysNew?: boolean): Client {
|
|
55
|
+ if (allwaysNew || !Client.instance) {
|
|
56
|
+ Client.instance = new Client(url, callback, binaryType);
|
|
57
|
+ }
|
|
58
|
+
|
|
59
|
+ return Client.instance;
|
|
60
|
+ }
|
|
61
|
+
|
|
62
|
+ /**
|
|
63
|
+ * 设置可以处理的数据包上限
|
|
64
|
+ * @param maxPayload 最多可以处理的数据包大小
|
|
65
|
+ */
|
|
66
|
+ public set maxPayload(maxPayload: number) {
|
|
67
|
+ this._maxPayload = maxPayload;
|
|
68
|
+ }
|
|
69
|
+
|
|
70
|
+ /**
|
|
71
|
+ * 获取可以处理的数据包大小
|
|
72
|
+ */
|
|
73
|
+ public get maxPayload(): number {
|
|
74
|
+ return this._maxPayload;
|
|
75
|
+ }
|
|
76
|
+
|
|
77
|
+ /**
|
|
78
|
+ * 设置是否允许显示运行日志
|
|
79
|
+ */
|
|
80
|
+ public set enableLogger(enableLogger: boolean) {
|
|
81
|
+ this._enableLogger = enableLogger;
|
|
82
|
+ }
|
|
83
|
+
|
|
84
|
+ /**
|
|
85
|
+ * 获取是否显示日志的配置信息
|
|
86
|
+ */
|
|
87
|
+ public get enableLogger(): boolean {
|
|
88
|
+ return this._enableLogger;
|
|
89
|
+ }
|
|
90
|
+
|
|
91
|
+ /**
|
|
92
|
+ * 发送ping请求,来保持长连接
|
|
93
|
+ * @param param 请求参数,比如{"hello":"world"}
|
|
94
|
+ */
|
|
95
|
+ public async ping(param: object): Promise<WebSocketResp> {
|
|
96
|
+ return new Promise(
|
|
97
|
+ (
|
|
98
|
+ resolve: (data: WebSocketResp) => void,
|
|
99
|
+ reject: (err: WebsocketError) => void,
|
|
100
|
+ ): void => {
|
|
101
|
+ if (this.socket.readyState !== this.socket.OPEN) {
|
|
102
|
+ if (this._enableLogger) {
|
|
103
|
+ console.log('[ping]: connection refuse');
|
|
104
|
+ }
|
|
105
|
+
|
|
106
|
+ reject(new WebsocketError(clientError, 'connection refuse'));
|
|
107
|
+ }
|
|
108
|
+
|
|
109
|
+ const heartbeatOperator = 0;
|
|
110
|
+
|
|
111
|
+ this.listeners.addListener(
|
|
112
|
+ heartbeatOperator.toString(),
|
|
113
|
+ (data: WebSocketResp): void => {
|
|
114
|
+ const code = this.getResponseProperty('code');
|
|
115
|
+ if (code !== '') {
|
|
116
|
+ const message = this.getResponseProperty('message');
|
|
117
|
+ reject(new WebsocketError(Number(code), message));
|
|
118
|
+ } else {
|
|
119
|
+ resolve(data);
|
|
120
|
+ }
|
|
121
|
+ },
|
|
122
|
+ );
|
|
123
|
+
|
|
124
|
+ const p = new Packet();
|
|
125
|
+ this.send(
|
|
126
|
+ p.pack(
|
|
127
|
+ heartbeatOperator,
|
|
128
|
+ 0,
|
|
129
|
+ this.requestHeader,
|
|
130
|
+ JSON.stringify(param),
|
|
131
|
+ ),
|
|
132
|
+ );
|
|
133
|
+
|
|
134
|
+ if (this._enableLogger) {
|
|
135
|
+ console.info(
|
|
136
|
+ '[send data packet]',
|
|
137
|
+ heartbeatOperator,
|
|
138
|
+ 0,
|
|
139
|
+ this.requestHeader,
|
|
140
|
+ param,
|
|
141
|
+ );
|
|
142
|
+ }
|
|
143
|
+ },
|
|
144
|
+ );
|
|
145
|
+ }
|
|
146
|
+
|
|
147
|
+ /**
|
|
148
|
+ * 同步方式向服务端发送请求
|
|
149
|
+ * @param operator 路由地址
|
|
150
|
+ * @param param 请求参数,比如{"hello":"world"}
|
|
151
|
+ * @param callback 请求状态回调处理
|
|
152
|
+ */
|
|
153
|
+ public async request(
|
|
154
|
+ operator: string,
|
|
155
|
+ param: object,
|
|
156
|
+ ): Promise<WebSocketResp> {
|
|
157
|
+ return await this.asyncSend(operator, param);
|
|
158
|
+ }
|
|
159
|
+
|
|
160
|
+ /**
|
|
161
|
+ * 添加消息监听
|
|
162
|
+ * @description 添加消息监听器,比如operator是/v1/message/listener,那么从服务端推送到/v1/message/listener的消息会进入到定义的listener里面进行处理
|
|
163
|
+ * @param operator 消息监听地址
|
|
164
|
+ * @param listener 定义如何处理从服务端返回的消息
|
|
165
|
+ */
|
|
166
|
+ public addMessageListener(
|
|
167
|
+ operator: string,
|
|
168
|
+ listener: (data: WebSocketResp) => void,
|
|
169
|
+ ): void {
|
|
170
|
+ this.listeners.addListener(Utils.crc32(operator).toString(), listener);
|
|
171
|
+ }
|
|
172
|
+
|
|
173
|
+ /**
|
|
174
|
+ * 移除消息监听
|
|
175
|
+ * @param operator 消息监听地址
|
|
176
|
+ */
|
|
177
|
+ public removeMessageListener(operator: string): void {
|
|
178
|
+ this.listeners.removeListener(Utils.crc32(operator).toString());
|
|
179
|
+ }
|
|
180
|
+
|
|
181
|
+ /**
|
|
182
|
+ * 返回Websocket链接状态
|
|
183
|
+ * @returns Websocket的链接状态
|
|
184
|
+ */
|
|
185
|
+ public get readyState(): number {
|
|
186
|
+ return this.socket.readyState;
|
|
187
|
+ }
|
|
188
|
+
|
|
189
|
+ /**
|
|
190
|
+ * 添加请求属性,会携带在数据帧里面发送到服务端
|
|
191
|
+ * @param key 属性名
|
|
192
|
+ * @param value 属性值
|
|
193
|
+ */
|
|
194
|
+ public setRequestProperty(key: string, value: string): void {
|
|
195
|
+ let v = this.getRequestProperty(key);
|
|
196
|
+
|
|
197
|
+ this.requestHeader = this.requestHeader.replace(key + '=' + v + ';', '');
|
|
198
|
+ this.requestHeader = this.requestHeader + key + '=' + value + ';';
|
|
199
|
+ }
|
|
200
|
+
|
|
201
|
+ /**
|
|
202
|
+ * 获取请求属性
|
|
203
|
+ * @param key 属性名
|
|
204
|
+ */
|
|
205
|
+ public getRequestProperty(key: string): string {
|
|
206
|
+ if (this.requestHeader !== undefined) {
|
|
207
|
+ let values = this.requestHeader.split(';');
|
|
208
|
+ for (let index in values) {
|
|
209
|
+ let kv = values[index].split('=');
|
|
210
|
+ if (kv[0] === key) {
|
|
211
|
+ return kv[1];
|
|
212
|
+ }
|
|
213
|
+ }
|
|
214
|
+ }
|
|
215
|
+
|
|
216
|
+ return '';
|
|
217
|
+ }
|
|
218
|
+
|
|
219
|
+ /**
|
|
220
|
+ * 设置响应属性,客户端基本用不到,都是服务端来进行设置
|
|
221
|
+ * @param key 属性名
|
|
222
|
+ * @param value 属性值
|
|
223
|
+ */
|
|
224
|
+ public setResponseProperty(key: string, value: string): void {
|
|
225
|
+ let v = this.getResponseProperty(key);
|
|
226
|
+
|
|
227
|
+ this.responseHeader = this.responseHeader.replace(key + '=' + v + ';', '');
|
|
228
|
+ this.responseHeader = this.responseHeader + key + '=' + value + ';';
|
|
229
|
+ }
|
|
230
|
+
|
|
231
|
+ /**
|
|
232
|
+ * 获取从服务端返回的属性
|
|
233
|
+ * @param key 获取响应属性
|
|
234
|
+ */
|
|
235
|
+ public getResponseProperty(key: string): string {
|
|
236
|
+ if (this.responseHeader !== undefined) {
|
|
237
|
+ let values = this.responseHeader.split(';');
|
|
238
|
+ for (let index in values) {
|
|
239
|
+ let kv = values[index].split('=');
|
|
240
|
+ if (kv[0] === key) {
|
|
241
|
+ return kv[1];
|
|
242
|
+ }
|
|
243
|
+ }
|
|
244
|
+ }
|
|
245
|
+
|
|
246
|
+ return '';
|
|
247
|
+ }
|
|
248
|
+ /**
|
|
249
|
+ * 关闭客户端链接
|
|
250
|
+ */
|
|
251
|
+ public close(code?: number, reason?: string): void {
|
|
252
|
+ // 如果是主动关闭
|
|
253
|
+ this.reconnectLock = true;
|
|
254
|
+ this.socket.close(code, reason);
|
|
255
|
+ }
|
|
256
|
+ /**
|
|
257
|
+ * 创建websocket链接
|
|
258
|
+ */
|
|
259
|
+ private connect(): WebSocket {
|
|
260
|
+ const readyStateCallback = this.readyStateCallback;
|
|
261
|
+ let ws = new WebSocket(this.url);
|
|
262
|
+
|
|
263
|
+ ws.binaryType = this.binaryType;
|
|
264
|
+
|
|
265
|
+ ws.onopen = (ev): void => {
|
|
266
|
+ if (this._enableLogger) {
|
|
267
|
+ console.info('[websocket] open connection');
|
|
268
|
+ }
|
|
269
|
+
|
|
270
|
+ this.reconnectTimes = 0;
|
|
271
|
+
|
|
272
|
+ readyStateCallback.onOpen(ev);
|
|
273
|
+ };
|
|
274
|
+
|
|
275
|
+ ws.onclose = (ev): void => {
|
|
276
|
+ if (this._enableLogger) {
|
|
277
|
+ console.info('[websocket] close connection');
|
|
278
|
+ }
|
|
279
|
+
|
|
280
|
+ this.reconnect();
|
|
281
|
+
|
|
282
|
+ readyStateCallback.onClose(ev);
|
|
283
|
+ };
|
|
284
|
+
|
|
285
|
+ ws.onerror = (ev): void => {
|
|
286
|
+ if (this._enableLogger) {
|
|
287
|
+ console.info('[websocket] error');
|
|
288
|
+ }
|
|
289
|
+
|
|
290
|
+ this.reconnect();
|
|
291
|
+
|
|
292
|
+ readyStateCallback.onError(ev);
|
|
293
|
+ };
|
|
294
|
+
|
|
295
|
+ ws.onmessage = (ev): void => {
|
|
296
|
+ const handleData = (data: ArrayBuffer) => {
|
|
297
|
+ try {
|
|
298
|
+ let packet = new Packet().unPack(data);
|
|
299
|
+ let packetLength = packet.headerLength + packet.bodyLength + 20;
|
|
300
|
+ if (packetLength > this._maxPayload) {
|
|
301
|
+ throw new Error('the packet is big than ' + this._maxPayload);
|
|
302
|
+ }
|
|
303
|
+
|
|
304
|
+ let operator = Number(packet.operator) + Number(packet.sequence);
|
|
305
|
+ let listener = operator.toString();
|
|
306
|
+
|
|
307
|
+ this.listeners.listeners(listener).forEach((param): void => {
|
|
308
|
+ if (packet.body === '') {
|
|
309
|
+ packet.body = '{}';
|
|
310
|
+ }
|
|
311
|
+
|
|
312
|
+ this.responseHeader = packet.header;
|
|
313
|
+
|
|
314
|
+ (param as (data: WebSocketResp) => void)(JSON.parse(packet.body));
|
|
315
|
+ });
|
|
316
|
+
|
|
317
|
+ if (this._enableLogger) {
|
|
318
|
+ if (operator !== 0 && packet.body !== 'null') {
|
|
319
|
+ console.info('receive data packet', packet.body);
|
|
320
|
+ }
|
|
321
|
+ }
|
|
322
|
+ } catch (e) {
|
|
323
|
+ throw new Error(e);
|
|
324
|
+ }
|
|
325
|
+ }
|
|
326
|
+ // 区分不同类型数据的解析(暂时支持Blob和ArrayBuffer)
|
|
327
|
+ if (ev.data instanceof Blob) {
|
|
328
|
+ let reader = new FileReader();
|
|
329
|
+ reader.readAsArrayBuffer(ev.data);
|
|
330
|
+ reader.onload = (): void => {
|
|
331
|
+ handleData(reader.result as ArrayBuffer)
|
|
332
|
+ };
|
|
333
|
+ } else if(ev.data instanceof ArrayBuffer) {
|
|
334
|
+ handleData(ev.data);
|
|
335
|
+ } else {
|
|
336
|
+ throw new Error('unsupported data format');
|
|
337
|
+ }
|
|
338
|
+ };
|
|
339
|
+
|
|
340
|
+ return ws;
|
|
341
|
+ }
|
|
342
|
+
|
|
343
|
+ /**`
|
|
344
|
+ * 断线重连
|
|
345
|
+ */
|
|
346
|
+ private reconnect(): void {
|
|
347
|
+ if (!this.reconnectLock) {
|
|
348
|
+ this.reconnectLock = true;
|
|
349
|
+ if (this._enableLogger) {
|
|
350
|
+ console.info('websocket reconnect in ' + this.reconnectTimes + 's');
|
|
351
|
+ }
|
|
352
|
+
|
|
353
|
+ // 尝试重连
|
|
354
|
+ setTimeout((): void => {
|
|
355
|
+ this.reconnectTimes++;
|
|
356
|
+ this.socket = this.connect();
|
|
357
|
+ this.reconnectLock = false;
|
|
358
|
+ }, this.reconnectTimes * 1000);
|
|
359
|
+ }
|
|
360
|
+ }
|
|
361
|
+
|
|
362
|
+ /**
|
|
363
|
+ * 向服务端发送数据请求
|
|
364
|
+ * @param data 向服务端传送的数据
|
|
365
|
+ */
|
|
366
|
+ private send(data: ArrayBuffer): void {
|
|
367
|
+ if (this.socket.readyState !== this.socket.OPEN) {
|
|
368
|
+ if (this._enableLogger) {
|
|
369
|
+ console.error(
|
|
370
|
+ '[send] WebSocket is already in CLOSING or CLOSED state.',
|
|
371
|
+ );
|
|
372
|
+ }
|
|
373
|
+
|
|
374
|
+ return;
|
|
375
|
+ }
|
|
376
|
+
|
|
377
|
+ try {
|
|
378
|
+ this.socket.send(data);
|
|
379
|
+ } catch (e) {
|
|
380
|
+ throw new Error('send data error' + e);
|
|
381
|
+ }
|
|
382
|
+ }
|
|
383
|
+
|
|
384
|
+ /**
|
|
385
|
+ * 异步向服务端发送请求
|
|
386
|
+ * @param operator 路由地址
|
|
387
|
+ * @param param 请求参数,比如{"hello":"world"}
|
|
388
|
+ * @param callback 请求状态回调处理
|
|
389
|
+ */
|
|
390
|
+ private asyncSend(operator: string, param: object): Promise<WebSocketResp> {
|
|
391
|
+ return new Promise(
|
|
392
|
+ (
|
|
393
|
+ resolve: (data: WebSocketResp) => void,
|
|
394
|
+ reject: (err: WebsocketError) => void,
|
|
395
|
+ ): void => {
|
|
396
|
+ if (this.socket.readyState !== this.socket.OPEN) {
|
|
397
|
+ if (this._enableLogger) {
|
|
398
|
+ console.log('[ping]: connection refuse');
|
|
399
|
+ }
|
|
400
|
+
|
|
401
|
+ reject(
|
|
402
|
+ new WebsocketError(clientError, 'asyncSend: connection refuse'),
|
|
403
|
+ );
|
|
404
|
+ }
|
|
405
|
+
|
|
406
|
+ const sequence = new Date().getTime();
|
|
407
|
+ const listener = Utils.crc32(operator) + sequence;
|
|
408
|
+ this.listeners.addListener(
|
|
409
|
+ listener.toString(),
|
|
410
|
+ (data: WebSocketResp): void => {
|
|
411
|
+ const code = this.getResponseProperty('code');
|
|
412
|
+ if (code !== '') {
|
|
413
|
+ const message = this.getResponseProperty('message');
|
|
414
|
+ reject(new WebsocketError(Number(code), message));
|
|
415
|
+ } else {
|
|
416
|
+ resolve(data);
|
|
417
|
+ }
|
|
418
|
+
|
|
419
|
+ delete this.listeners[listener];
|
|
420
|
+ },
|
|
421
|
+ );
|
|
422
|
+
|
|
423
|
+ const p = new Packet();
|
|
424
|
+ this.send(
|
|
425
|
+ p.pack(
|
|
426
|
+ Utils.crc32(operator),
|
|
427
|
+ sequence,
|
|
428
|
+ this.requestHeader,
|
|
429
|
+ JSON.stringify(param),
|
|
430
|
+ ),
|
|
431
|
+ );
|
|
432
|
+
|
|
433
|
+ if (this._enableLogger) {
|
|
434
|
+ console.info(
|
|
435
|
+ '[send data packet]',
|
|
436
|
+ operator,
|
|
437
|
+ sequence,
|
|
438
|
+ this.requestHeader,
|
|
439
|
+ param,
|
|
440
|
+ );
|
|
441
|
+ }
|
|
442
|
+ },
|
|
443
|
+ );
|
|
444
|
+ }
|
|
445
|
+}
|
|
446
|
+
|
|
447
|
+export { Client };
|