package udp import ( "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 } // 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 // 启动监听处理 go s.listenAndHandle() } func (s *server) Close() { err := s.conn.Close() if err != nil { slog.Error("udp server close error", "error", err) } } func (s *server) listenAndHandle() { defer s.conn.Close() for { b := make([]byte, 1024) n, err := s.conn.Read(b) if err != nil { slog.Error("udp server read error", err) return } if n > 0 { go s.handle(b[0: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) }