63 lines
1.0 KiB
Go
63 lines
1.0 KiB
Go
|
package udp
|
||
|
|
||
|
import (
|
||
|
"log/slog"
|
||
|
"net"
|
||
|
)
|
||
|
|
||
|
type UdpServer interface {
|
||
|
Listen()
|
||
|
}
|
||
|
|
||
|
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) 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", err)
|
||
|
}
|
||
|
}()
|
||
|
// slog.Info("udp server handle", "msg", string(b))
|
||
|
s.handler(b)
|
||
|
}
|