Files
mayhem-party/src/device/input/raw/udp.go
2023-03-25 10:58:13 -06:00

64 lines
945 B
Go

package raw
import (
"context"
"log"
"net"
"os"
"strconv"
)
var (
FlagDebug = os.Getenv("DEBUG") == "true"
)
type UDP struct {
conn net.PacketConn
c chan []byte
ctx context.Context
}
func NewUDP(ctx context.Context, port int) UDP {
conn, err := net.ListenPacket("udp", ":"+strconv.Itoa(port))
if err != nil {
panic(err)
}
result := UDP{
conn: conn,
c: make(chan []byte, 8),
ctx: ctx,
}
go result.listen()
return result
}
func (udp UDP) listen() {
for udp.ctx.Err() == nil {
buff := make([]byte, 256)
n, _, err := udp.conn.ReadFrom(buff)
if err != nil && udp.ctx.Err() == nil {
panic(err)
}
if FlagDebug {
log.Printf("raw.UDP.Read() => %s", buff[:n])
}
select {
case udp.c <- buff[:n]:
case <-udp.ctx.Done():
}
}
}
func (udp UDP) Read() []byte {
select {
case v := <-udp.c:
return v
case <-udp.ctx.Done():
return []byte{}
}
}
func (udp UDP) Close() {
udp.conn.Close()
}