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()
}
if port, _ := strconv.Atoi(os.Getenv("RAW_UDP")); port != 0 {
return NewUDP(port)
return NewUDP(ctx, port)
}
generator := randomCharFromRange('a', 'g')
if p, ok := os.LookupEnv("RAW_RANDOM_WEIGHT_FILE"); ok && len(p) > 0 {

View File

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