-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
64 lines (59 loc) · 1.27 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
package bttcp
import (
"bufio"
"errors"
"fmt"
"github.com/go-needle/bttcp/proto"
"net"
"sync"
)
type Client struct {
address string
poolSize int
pool *Pool
once sync.Once
}
func NewClient(address string, poolSize int, isTestConn bool) *Client {
if isTestConn {
conn, err := net.Dial("tcp", address)
if err != nil {
panic(errors.New(fmt.Sprintf("dial bttcp %s: connect: connection refused", address)))
}
_, err = conn.Write(nil)
if err != nil {
panic(errors.New(fmt.Sprintf("dial bttcp %s: connect: connection refused", address)))
}
err = conn.Close()
if err != nil {
panic(errors.New(fmt.Sprintf("dial bttcp %s: connect: connection refused", address)))
}
}
return &Client{address: address, poolSize: poolSize}
}
func (c *Client) Send(b []byte) ([]byte, error) {
c.once.Do(func() {
c.pool = NewPool(c.poolSize, c.address)
})
conn, err := c.pool.GetConnection()
defer c.pool.ReleaseConnection(conn)
if err != nil {
return nil, err
}
data, err := proto.Encode(b)
if err != nil {
return nil, err
}
_, err = conn.Write(data)
if err != nil {
return nil, err
}
reader := bufio.NewReader(conn)
rb, err := proto.Decode(reader)
if err != nil {
return nil, err
}
return rb, nil
}
func (c *Client) Close() {
c.pool.ClearPool()
}