mirror of
https://github.com/ehang-io/nps.git
synced 2025-09-02 20:16:52 +00:00
Code optimization
This commit is contained in:
50
lib/conn/listener.go
Normal file
50
lib/conn/listener.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func NewTcpListenerAndProcess(addr string, f func(c net.Conn), listener *net.Listener) error {
|
||||
var err error
|
||||
*listener, err = net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
Accept(*listener, f)
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewKcpListenerAndProcess(addr string, f func(c net.Conn)) error {
|
||||
kcpListener, err := kcp.ListenWithOptions(addr, nil, 150, 3)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return err
|
||||
}
|
||||
for {
|
||||
c, err := kcpListener.AcceptKCP()
|
||||
SetUdpSession(c)
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
go f(c)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Accept(l net.Listener, f func(c net.Conn)) {
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
go f(c)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user