rts-sim-testing-service/third_party/udp/udp_server.go
walker 62b44a0cc6 添加UDP网络延时记录器
动力学和半实物接口添加UDP网络监控功能
2024-01-22 13:10:10 +08:00

83 lines
1.6 KiB
Go

package udp
import (
"context"
"log/slog"
"net"
"runtime/debug"
)
type UdpServer interface {
Listen()
Close()
}
type UdpMsgHandler func(b []byte)
type server struct {
addr string
conn *net.UDPConn
handler UdpMsgHandler
cancelFn context.CancelFunc
}
// NewServer creates a new instance of UdpServer.
func NewServer(addr string, handler UdpMsgHandler) UdpServer {
return &server{addr: addr, handler: handler}
}
func (s *server) Listen() {
udpAddr, err := net.ResolveUDPAddr("udp", s.addr)
if err != nil {
panic(err)
}
conn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
panic(err)
}
s.conn = conn
ctx, cfn := context.WithCancel(context.Background())
// 启动监听处理
go s.listenAndHandle(ctx)
s.cancelFn = cfn
}
func (s *server) Close() {
s.cancelFn()
// err := s.conn.Close()
// if err != nil {
// slog.Error("udp server close error", "error", err)
// }
}
func (s *server) listenAndHandle(ctx context.Context) {
defer s.conn.Close()
for {
select {
case <-ctx.Done():
slog.Info("udp server listen 关闭", "addr", s.addr)
return
default:
}
buf := make([]byte, 1024)
n, _, err := s.conn.ReadFromUDP(buf)
if err != nil {
slog.Error("udp server read error", "addr", s.addr, "error", err)
continue
}
// slog.Debug("udp server handle", "addr", ap.String())
go s.handle(buf[:n])
}
}
func (s *server) handle(b []byte) {
defer func() {
if err := recover(); err != nil {
slog.Error("udp server handle error", "error", err, "stack", string(debug.Stack()))
debug.PrintStack()
}
}()
// slog.Info("udp server handle", "msg", string(b))
s.handler(b)
}