-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
96 lines (75 loc) · 1.48 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package valve
import (
"fmt"
"time"
"github.com/oxxzz/valve/socket"
)
// Client is a client for the Valve source query protocol
type Client struct {
socket *socket.Udp
timeout time.Duration
connected bool
}
// NewClient creates a new client
func NewClient(addr string, timeout time.Duration) (*Client, error) {
socket, err := socket.NewUdp(addr, timeout)
if err != nil {
return nil, err
}
return &Client{socket: socket, timeout: timeout, connected: true}, nil
}
// Close closes the underlying socket
func (c *Client) Close() error {
if c.connected {
c.connected = false
return c.socket.Close()
}
return nil
}
func (c *Client) Reconnect() error {
c.Close()
return c.Connect()
}
func (c *Client) Connect() error {
if c.connected {
return nil
}
err := c.socket.Connect()
if err != nil {
c.connected = false
return err
}
c.connected = true
return nil
}
func Try(fn func() error) error {
var outErr error
(func() {
defer func() {
if r := recover(); r != nil {
err, ok := r.(error)
if !ok {
err = fmt.Errorf("%v", r)
}
outErr = err
}
}()
outErr = fn()
})()
return outErr
}
type MultiPacketHeader struct {
// Size of the packet header itself.
Size int
// Packet sequence id.
Id uint32
// Packet number out of Total Packets.
PacketNumber uint8
// Total number of packets to receive.
TotalPackets uint8
// Packet size (0 if not present).
PacketSize uint16
// Compression information.
Compressed bool
Payload []byte
}