-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbw2.go
63 lines (59 loc) · 1.26 KB
/
bw2.go
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
package bw2bind
import (
"bufio"
"net"
"sync"
)
// BW2Client is a handle to your local BOSSWAVE router. It is obtained
// from Connect or ConnectOrExit
type BW2Client struct {
c net.Conn
out *bufio.Writer
in *bufio.Reader
remotever string
seqnos map[int]chan *frame
olock sync.Mutex
curseqno uint32
defAutoChain *bool
rHost string
}
func (cl *BW2Client) Close() error {
return cl.c.Close()
}
//Sends a request frame and returns a chan that contains all the responses.
//Automatically closes the returned channel when there are no more responses.
func (cl *BW2Client) transact(req *frame) chan *frame {
seqno := req.SeqNo
inchan := make(chan *frame, 3)
outchan := make(chan *frame, 3)
cl.olock.Lock()
cl.seqnos[seqno] = inchan
req.WriteToStream(cl.out)
cl.olock.Unlock()
go func() {
for {
fr, ok := <-inchan
if !ok {
close(outchan)
return
}
outchan <- fr
finished, ok := fr.GetFirstHeader("finished")
if ok && finished == "true" {
close(outchan)
cl.closeSeqno(fr.SeqNo)
return
}
}
}()
return outchan
}
func (cl *BW2Client) closeSeqno(seqno int) {
cl.olock.Lock()
ch, ok := cl.seqnos[seqno]
if ok {
close(ch)
delete(cl.seqnos, seqno)
}
cl.olock.Unlock()
}