-
-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathsender.js
87 lines (77 loc) · 1.9 KB
/
sender.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
75
76
77
78
79
80
81
82
83
84
85
86
87
const debug = require('debug')('wx-ws:sender');
/**
* Sender
*/
class Sender {
/**
* Create a Sender instance
*
* @param {*} socket The connection socket of wx
*/
constructor(socket) {
this._socket = socket;
this._queue = []
this._bufferedBytes = 0;
this._deflating = false;
}
/**
* Sends a data message to the other peer.
*
* @param {*} data
* @param {*} options
* @param {*} cb
*/
send(data, options, cb) {
debug("send msg: ", data, ' sender: ', this, this._deflating)
if (this._deflating) {
this.enqueue([this.dispatch, data, options, cb]);
} else {
this.dispatch(data, options, cb);
}
}
/**
* Dispatches a data message.
*
* @param {*} data
* @param {*} options
* @param {*} cb
*/
dispatch(data, options, cb) {
debug("dispatch msg: ", data, ', sender: ', this)
this._deflating = true;
if (typeof options === 'function') {
cb = options;
options = {};
}
this._deflating = false;
this._socket.send({
data: data,
success: res => cb && cb(null, res),
fail: err => cb && cb(err)
})
this.dequeue();
}
/**
* Executes queued send operations.
*
* @private
*/
dequeue() {
while (!this._deflating && this._queue.length) {
const params = this._queue.shift();
this._bufferedBytes -= params[1].length;
Reflect.apply(params[0], this, params.slice(1));
}
}
/**
* Enqueues a send operation.
*
* @param {Array} params Send operation parameters.
* @private
*/
enqueue(params) {
this._bufferedBytes += params[1].length;
this._queue.push(params);
}
}
module.exports = Sender;