-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
104 lines (81 loc) · 2.45 KB
/
Copy pathindex.js
File metadata and controls
104 lines (81 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
export class WrappedWxSocket {
static CONNECTING = 0;
static OPEN = 1;
static CLOSING = 2;
static CLOSED = 3;
constructor(url, protocols) {
// FIXME 小程序接口与标准 Websocket 对象不完全一致,因此要做兼容处理
const options = {
url,
protocols: typeof protocols === "string" ? [protocols] : protocols,
};
this.socketOptions = options;
this.url = url;
this.protocols = options.protocols;
this.socketTask = wx.connectSocket(options);
this.syncReadyState();
this.onOpenCallback = function () { };
this.socketTask.onOpen(event => {
this.syncReadyState();
this.onOpenCallback.call(this, event);
});
this.onErrorCallback = function () { };
this.socketTask.onError(error => {
this.syncReadyState();
// 但微信小程序则只会触发error,为了保证socket在出了问题后能及时重连,这里手动触发一次close
setTimeout(() => {
this.onCloseCallback();
}, 0);
this.onErrorCallback.call(this, error);
});
this.onMessageCallback = function () { };
this.socketTask.onMessage(data => {
this.syncReadyState();
this.onMessageCallback.call(this, data);
});
this.onCloseCallback = function () { };
this.socketTask.onClose(event => {
this.syncReadyState();
this.onCloseCallback.call(this, event);
});
}
syncReadyState() {
this.readyState = this.socketTask.readyState;
}
set onopen(callback) {
this.onOpenCallback = callback;
}
get onopen() {
return this.onOpenCallback;
}
set onerror(callback) {
this.onErrorCallback = callback;
}
get onerror() {
return this.onErrorCallback;
}
set onmessage(callback) {
this.onMessageCallback = callback;
}
get onmessage() {
return this.onMessageCallback;
}
set onclose(callback) {
this.onCloseCallback = callback;
}
get onclose() {
return this.onCloseCallback;
}
close() {
if (this.socketTask.readyState < 2) {
this.socketTask.close();
}
this.syncReadyState();
}
send(data) {
this.socketTask.send({
data,
});
this.syncReadyState();
}
}