-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudp.go
41 lines (34 loc) · 823 Bytes
/
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
package wrc
import (
"bytes"
"encoding/binary"
"net"
"os"
"github.com/charmbracelet/log"
)
var logger = log.NewWithOptions(os.Stderr, log.Options{
Prefix: "UDP",
})
//Listen is a function that listens for incoming packets on a given connection.
//It reads the packets into a buffer, decodes them into a Packet struct, and sends them on a channel.
//
// go Listen(conn,ch)
// ch: The channel to send the decoded packets on.
//
func Listen(conn net.PacketConn, ch chan Packet) error {
buf := make([]byte, binary.Size(Packet{}))
for {
_, _, err := conn.ReadFrom(buf)
if err != nil {
logger.Error(err)
return ErrUDPData
}
var packet Packet
err = binary.Read(bytes.NewReader(buf), binary.LittleEndian, &packet)
if err != nil {
logger.Error(err)
return ErrUDPData
}
ch <- packet
}
}