forked from ehang-io/nps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlistener.go
50 lines (46 loc) · 939 Bytes
/
listener.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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)
}
}