github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/network/udp_listener.go (about) 1 package network 2 3 import ( 4 "github.com/15mga/kiwi" 5 "net" 6 7 "github.com/15mga/kiwi/util" 8 "github.com/xtaci/kcp-go/v5" 9 ) 10 11 func NewUdpListener(addr string, onConn func(conn net.Conn)) kiwi.IListener { 12 return &udpListener{ 13 addr: addr, 14 onConn: onConn, 15 } 16 } 17 18 type udpListener struct { 19 addr string 20 onConn func(conn net.Conn) 21 listener *kcp.Listener 22 } 23 24 func (l *udpListener) Addr() string { 25 return l.addr 26 } 27 28 func (l *udpListener) Port() int { 29 port, _ := util.ParseAddrPort(l.listener.Addr().String()) 30 return port 31 } 32 33 func (l *udpListener) Start() *util.Err { 34 kiwi.Info("start udp listener", util.M{ 35 "addr": l.addr, 36 }) 37 listener, err := kcp.Listen(l.addr) 38 if err != nil { 39 return util.NewErr(util.EcListenErr, util.M{ 40 "addr": l.addr, 41 "error": err.Error(), 42 }) 43 } 44 45 l.listener = listener.(*kcp.Listener) 46 go func() { 47 for { 48 conn, err := l.listener.AcceptKCP() 49 if err != nil { 50 kiwi.Error2(util.EcAcceptErr, util.M{ 51 "error": err.Error(), 52 }) 53 return 54 } 55 56 l.onConn(conn) 57 } 58 }() 59 return nil 60 } 61 62 func (l *udpListener) Close() { 63 if l.listener == nil { 64 return 65 } 66 l.listener.Close() 67 }