-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
53 lines (43 loc) · 1.31 KB
/
client.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
var multiplex = require('multiplex')
var timers = require('timers')
var wrapStream = require('./util').wrapStream
module.exports = function createClient () {
var waitingChannels = {}
var multiplexStream = multiplex(onConnection)
multiplexStream.channel = channel
return multiplexStream
function channel (payload, cb) {
var negotiationStream = wrapStream(multiplexStream.createStream())
negotiationStream.once('data', onNegotiationReply)
negotiationStream.write(payload)
function onNegotiationReply (reply) {
var err = reply[0]
var channelId = reply[1]
if (err) {
cb(err)
} else {
var channel = waitingChannels[channelId]
/* istanbul ignore else */
if (channel) {
delete waitingChannels[channelId]
timers.setImmediate(cb, null, channel)
} else {
waitForChannel(channelId, cb)
}
}
}
}
function onConnection (channel, channelId) {
var cb = waitingChannels[channelId]
/* istanbul ignore if */
if (cb) {
delete waitingChannels[channelId]
timers.setImmediate(cb, null, wrapStream(channel))
} else {
waitForChannel(channelId, wrapStream(channel))
}
}
function waitForChannel (channelId, connection) {
waitingChannels[channelId] = connection
}
}