-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.go
75 lines (64 loc) · 1.09 KB
/
client.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
64
65
66
67
68
69
70
71
72
73
74
75
package smux
import (
"bytes"
"io"
"sync"
)
type Client struct {
sync.Mutex
Network string
Address string
conn *Conn
}
func (c *Client) Post(b []byte) ([]byte, error) {
stream, err := c.getStream()
if err != nil {
return nil, err
}
_, err = stream.WriteOnce(b)
if err != nil {
return nil, err
}
go stream.Poll()
var buf bytes.Buffer
out := make([]byte, 1024)
for {
n, err := stream.Read(out)
if err == io.EOF {
break
}
buf.Write(out[:n])
}
return buf.Bytes(), nil
}
func (c *Client) getStream() (Stream, error) {
c.Lock()
defer c.Unlock()
conn, err := c.getConn(false)
if err != nil {
return Stream{}, err
}
stream, err := conn.Stream()
if err == ExceedError {
conn, err := c.getConn(true)
if err != nil {
return Stream{}, err
}
return conn.Stream()
}
return stream, err
}
func (c *Client) getConn(force bool) (*Conn, error) {
if c.conn == nil || force {
conn, err := Dial(c.Network, c.Address)
if err != nil {
return nil, err
}
if c.conn != nil {
c.conn.Close()
}
go conn.Listen()
c.conn = &conn
}
return c.conn, nil
}