udp in bg thread
parent
2af373aed7
commit
aa16b66332
|
|
@ -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 {
|
||||||
|
|
|
||||||
|
|
@ -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) 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 {
|
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")
|
return <-udp.c
|
||||||
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]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (udp UDP) Close() {
|
func (udp UDP) Close() {
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue