forked from sostronk/go-steam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udpsocket.go
62 lines (54 loc) · 1.12 KB
/
udpsocket.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
package steam
import (
"errors"
"fmt"
"net"
"time"
)
type udpSocket struct {
conn net.Conn
}
func newUDPSocket(dial DialFn, addr string) (*udpSocket, error) {
conn, err := dial("udp", addr)
if err != nil {
return nil, err
}
return &udpSocket{conn}, nil
}
func (s *udpSocket) close() {
s.conn.Close()
}
func (s *udpSocket) send(payload []byte) error {
n, err := s.conn.Write(payload)
if err != nil {
return err
}
if n != len(payload) {
return fmt.Errorf("steam: could not send full udp request to %v", s.conn.RemoteAddr())
}
return nil
}
func (s *udpSocket) receivePacket() ([]byte, error) {
if err := s.conn.SetReadDeadline(time.Now().Add(1 * time.Second)); err != nil {
return nil, err
}
buf := make([]byte, 1500)
n, err := s.conn.Read(buf)
if err != nil {
return nil, err
}
return buf[:n], nil
}
func (s *udpSocket) receive() ([]byte, error) {
buf, err := s.receivePacket()
if err != nil {
return nil, err
}
if buf[0] == 0xFE {
return nil, errors.New("steam: cannot handle split packets")
}
if len(buf) < 4 {
return nil, errors.New("steam: invalid buffer size")
}
return buf[4:], nil
}