-
Notifications
You must be signed in to change notification settings - Fork 1
/
udp.go
75 lines (67 loc) · 1.66 KB
/
udp.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 gosc
import (
"bufio"
"bytes"
"errors"
"net"
)
type transportUDP struct {
conn net.PacketConn
bufferSize int
}
// NewUDPTransport returns the default UDP Transport for clients.
func NewUDPTransport(address string, bufferSize int) (Transport, error) {
conn, err := net.Dial("udp", address)
if err != nil {
return nil, err
}
return &transportUDP{
conn: conn.(net.PacketConn),
bufferSize: bufferSize,
}, nil
}
// NewUDPListen returns the default UDP Transport for servers.
func NewUDPListen(address string, bufferSize int) (Transport, error) {
conn, err := net.ListenPacket("udp", address)
if err != nil {
return nil, err
}
return &transportUDP{
conn: conn,
bufferSize: bufferSize,
}, nil
}
// Send uses buffering to send a complete Package on the UDP socket.
func (t *transportUDP) Send(pack Package, addr net.Addr) error {
buf := bytes.Buffer{}
w := bufio.NewWriter(&buf)
err := writePackage(pack, w)
if err != nil {
return err
}
_ = w.Flush()
_, err = t.conn.WriteTo(buf.Bytes(), addr)
if errors.Is(err, net.ErrWriteToConnected) {
conn := t.conn.(*net.UDPConn)
_, err = conn.Write(buf.Bytes())
}
if err != nil {
return err
}
return nil
}
// Receive reads the UDP socket buffered and returns a Package when found.
func (t *transportUDP) Receive() (pack Package, from net.Addr, err error) {
buf := make([]byte, t.bufferSize)
_, from, err = t.conn.ReadFrom(buf)
if err != nil {
return nil, from, err
}
r := bufio.NewReaderSize(bytes.NewReader(buf), len(buf))
pack, err = readPackage(r)
return pack, from, err
}
// Close closes the underlying conn
func (t *transportUDP) Close() error {
return t.conn.Close()
}