-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
80 lines (73 loc) · 1.41 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package cnet
import (
"golang.org/x/sys/unix"
"net"
"os"
"sync"
)
type tcpListener struct {
f *os.File
fd int
ln net.Listener
once sync.Once
}
type udpListener struct {
f *os.File
fd int
ln net.PacketConn
once sync.Once
}
func (ln *tcpListener) initFd() error {
var err error
if ln.f, err = ln.ln.(*net.TCPListener).File(); err != nil {
ln.close()
return err
}
ln.fd = int(ln.f.Fd())
// 设置非阻塞
return unix.SetNonblock(ln.fd, true)
}
func (ln *udpListener) initFd() error {
var err error
switch pconn := ln.ln.(type) {
case *net.UDPConn:
ln.f, err = pconn.File()
}
if err != nil {
ln.close()
panic(err)
}
ln.fd = int(ln.f.Fd())
// 设置非阻塞
return unix.SetNonblock(ln.fd, true)
}
func (ln *udpListener) close() {
ln.once.Do(func() {
var err error
if ln.f != nil {
if err = ln.f.Close(); err != nil {
defaultLogger.Printf("udpListener fd close error: %v\n", err)
}
}
if ln.ln != nil {
if err = ln.ln.Close(); err != nil {
defaultLogger.Printf("udpListener fd close error: %v\n", err)
}
}
})
}
func (ln *tcpListener) close() {
ln.once.Do(func() {
var err error
if ln.f != nil {
if err = ln.f.Close(); err != nil {
defaultLogger.Printf("tcpListener fd close error: %v\n", err)
}
}
if ln.ln != nil {
if err = ln.ln.Close(); err != nil {
defaultLogger.Printf("tcpListener fd close error : %v\n", err)
}
}
})
}