1 | import { isFunction } from '@tarojs/shared';
|
2 |
|
3 | class SocketTask {
|
4 | constructor(url, protocols) {
|
5 | if (protocols && protocols.length) {
|
6 | this.ws = new WebSocket(url, protocols);
|
7 | }
|
8 | else {
|
9 | this.ws = new WebSocket(url);
|
10 | }
|
11 | this.CONNECTING = 0;
|
12 | this.OPEN = 1;
|
13 | this.CLOSING = 2;
|
14 | this.CLOSED = 3;
|
15 | }
|
16 | get readyState() {
|
17 | return this.ws.readyState;
|
18 | }
|
19 | send(opts = {}) {
|
20 | if (typeof opts !== 'object' || !opts)
|
21 | opts = {};
|
22 | const { data = '', success, fail, complete } = opts;
|
23 | if (this.readyState !== 1) {
|
24 | const res = { errMsg: 'SocketTask.send:fail SocketTask.readState is not OPEN' };
|
25 | console.error(res.errMsg);
|
26 | isFunction(fail) && fail(res);
|
27 | isFunction(complete) && complete(res);
|
28 | return Promise.reject(res);
|
29 | }
|
30 | this.ws.send(data);
|
31 | const res = { errMsg: 'sendSocketMessage:ok' };
|
32 | isFunction(success) && success(res);
|
33 | isFunction(complete) && complete(res);
|
34 | return Promise.resolve(res);
|
35 | }
|
36 | close(opts = {}) {
|
37 | if (typeof opts !== 'object' || !opts)
|
38 | opts = {};
|
39 | const { code = 1000, reason = 'server complete,close', success, complete } = opts;
|
40 | this.closeDetail = { code, reason };
|
41 |
|
42 | this._destroyWhenClose && this._destroyWhenClose();
|
43 | this.ws.close();
|
44 | const res = { errMsg: 'closeSocket:ok' };
|
45 | isFunction(success) && success(res);
|
46 | isFunction(complete) && complete(res);
|
47 | return Promise.resolve(res);
|
48 | }
|
49 | onOpen(func) {
|
50 | this.ws.onopen = func;
|
51 | }
|
52 | onMessage(func) {
|
53 | this.ws.onmessage = func;
|
54 | }
|
55 | onClose(func) {
|
56 | this.ws.onclose = () => {
|
57 |
|
58 | this._destroyWhenClose && this._destroyWhenClose();
|
59 | func(this.closeDetail || { code: 1006, reason: 'abnormal closure' });
|
60 | };
|
61 | }
|
62 | onError(func) {
|
63 | this.ws.onerror = func;
|
64 | }
|
65 | }
|
66 |
|
67 | export { SocketTask };
|
68 |
|