udp in bg thread

master
bel 2023-03-24 21:02:47 -06:00
parent 2af373aed7
commit aa16b66332
2 changed files with 26 additions and 13 deletions

View File

@ -16,7 +16,7 @@ func New(ctx context.Context) Raw {
return NewKeyboard() return NewKeyboard()
} }
if port, _ := strconv.Atoi(os.Getenv("RAW_UDP")); port != 0 { if port, _ := strconv.Atoi(os.Getenv("RAW_UDP")); port != 0 {
return NewUDP(port) return NewUDP(ctx, port)
} }
generator := randomCharFromRange('a', 'g') generator := randomCharFromRange('a', 'g')
if p, ok := os.LookupEnv("RAW_RANDOM_WEIGHT_FILE"); ok && len(p) > 0 { if p, ok := os.LookupEnv("RAW_RANDOM_WEIGHT_FILE"); ok && len(p) > 0 {

View File

@ -1,6 +1,7 @@
package raw package raw
import ( import (
"context"
"log" "log"
"net" "net"
"os" "os"
@ -9,29 +10,41 @@ import (
type UDP struct { type UDP struct {
conn net.PacketConn conn net.PacketConn
c chan []byte
ctx context.Context
} }
func NewUDP(port int) UDP { func NewUDP(ctx context.Context, port int) UDP {
conn, err := net.ListenPacket("udp", ":"+strconv.Itoa(port)) conn, err := net.ListenPacket("udp", ":"+strconv.Itoa(port))
if err != nil { if err != nil {
panic(err) panic(err)
} }
return UDP{ result := UDP{
conn: conn, conn: conn,
c: make(chan []byte, 8),
ctx: ctx,
} }
go result.listen()
return result
} }
func (udp UDP) Read() []byte { func (udp UDP) listen() {
panic("NEEDS TO BE IN BG THREAD SO WE CAN SHUT DOWN WITHOUT BLOCKING ON READ OR AT LEAST BE RESPONSIVE") debugging := os.Getenv("DEBUG") == "true"
buff := make([]byte, 1024) for udp.ctx.Err() == nil {
buff := make([]byte, 256)
n, _, err := udp.conn.ReadFrom(buff) n, _, err := udp.conn.ReadFrom(buff)
if err != nil { if err != nil {
panic(err) panic(err)
} }
if os.Getenv("DEBUG") == "true" { if debugging {
log.Printf("raw.UDP.Read() => %s", buff[:n]) log.Printf("raw.UDP.Read() => %s", buff[:n])
} }
return buff[:n] udp.c <- buff[:n]
}
}
func (udp UDP) Read() []byte {
return <-udp.c
} }
func (udp UDP) Close() { func (udp UDP) Close() {