-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
90 lines (68 loc) · 1.99 KB
/
connection.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package rcon
import (
"bufio"
"github.com/pkg/errors"
"github.com/refractorgscm/rcon/errs"
"github.com/refractorgscm/rcon/packet"
"strings"
"time"
)
func (c *Client) sendPacket(p packet.Packet) error {
out, err := p.Build()
if err != nil {
return errors.Wrap(err, "could not build packet")
}
if err := c.write(out); err != nil {
return errors.Wrap(err, "could not send authentication packet")
}
return nil
}
func (c *Client) readPacket() (packet.Packet, error) {
if c.conn == nil {
return nil, errs.ErrNotConnected
}
if err := c.conn.SetDeadline(time.Time{}); err != nil {
if strings.HasSuffix(err.Error(), "use of closed network connection") {
return nil, errs.ErrNotConnected
}
return nil, errors.Wrap(err, "could not set connection deadline")
}
reader := bufio.NewReader(c.conn)
res, err := packet.DecodeClientPacket(c.EndianMode, reader)
if err != nil {
if strings.HasSuffix(err.Error(), "use of closed network connection") {
return nil, errs.ErrNotConnected
}
return nil, errors.Wrap(err, "could not read packet")
}
c.log.Debug("Read packet ID: ", res.ID(), ", Body: ", string(res.Body()))
return res, nil
}
func (c *Client) readPacketTimeout() (packet.Packet, error) {
if c.conn == nil {
return nil, errs.ErrNotConnected
}
if err := c.conn.SetDeadline(time.Now().Add(c.ConnTimeout)); err != nil {
if strings.HasSuffix(err.Error(), "use of closed network connection") {
return nil, errs.ErrNotConnected
}
return nil, errors.Wrap(err, "could not set connection deadline")
}
reader := bufio.NewReader(c.conn)
res, err := packet.DecodeClientPacket(c.EndianMode, reader)
if err != nil {
if strings.HasSuffix(err.Error(), "use of closed network connection") {
return nil, errs.ErrNotConnected
}
return nil, errors.Wrap(err, "could not read packet")
}
return res, nil
}
func (c *Client) write(data []byte) error {
c.connLock.Lock()
defer c.connLock.Unlock()
if _, err := c.conn.Write(data); err != nil {
return err
}
return nil
}