-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (62 loc) · 1.48 KB
/
index.js
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
/* eslint-disable no-undef */
const SOCKET_STATES = { connecting: 0, open: 1, closing: 2, closed: 3 };
export default class WxSocket {
constructor(endPoint) {
this.endPoint = endPoint;
this.onopen = function() {}; // noop
this.onerror = function() {}; // noop
this.onmessage = function() {}; // noop
this.onclose = function() {}; // noop
this.readyState = SOCKET_STATES.connecting;
this.connect();
}
closeAndRetry() {
this.close();
this.readyState = SOCKET_STATES.connecting;
}
connect() {
if (
!(
this.readyState === SOCKET_STATES.open ||
this.readyState === SOCKET_STATES.connecting
)
) {
return;
}
wx.connectSocket({
url: this.endPoint
});
const _this = this;
wx.onSocketOpen(function(res) {
_this.readyState = SOCKET_STATES.open;
_this.onopen();
});
wx.onSocketError(function(res) {
_this.closeAndRetry();
_this.onerror();
});
wx.onSocketMessage(function(res) {
_this.onmessage({ data: res.data });
});
wx.onSocketClose(function(res) {
_this.close();
});
}
send(body) {
const _this = this;
wx.sendSocketMessage({
data: body,
success: function() {},
fail: function(res) {
_this.onerror();
_this.closeAndRetry();
},
complete: function() {}
});
}
close(code, reason) {
wx.closeSocket();
this.readyState = SOCKET_STATES.closed;
this.onclose();
}
}