-
Notifications
You must be signed in to change notification settings - Fork 22
/
server_linux.go
138 lines (111 loc) · 2.44 KB
/
server_linux.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
//go:build linux
// +build linux
package fastudp
import (
"fmt"
"net"
"runtime"
"sync"
"sync/atomic"
"github.com/shaoyuan1943/fastudp/netpoll"
"github.com/shaoyuan1943/fastudp/netudp"
)
type Server struct {
wg sync.WaitGroup
handler EventHandler
loops map[int]*eventLoop
wp chan []byte
pool sync.Pool
closed atomic.Value
lockThread bool
sync.Mutex
}
func NewUDPServer(network, addr string, reusePort bool, listenerN int, mtu int, handler EventHandler, enableLockThread bool) (*Server, error) {
if !netudp.IsUDP(network) {
return nil, fmt.Errorf("unknown network: %v", network)
}
svr := &Server{
handler: handler,
loops: make(map[int]*eventLoop),
wp: make(chan []byte, WriteEventSize),
lockThread: enableLockThread,
}
svr.pool.New = func() interface{} {
return make([]byte, mtu)
}
if reusePort {
if listenerN <= 0 {
listenerN = runtime.NumCPU()
}
} else {
listenerN = 1
}
if err := svr.start(network, addr, reusePort, listenerN, mtu); err != nil {
return nil, err
}
svr.closed.Store(false)
return svr, nil
}
func (s *Server) start(network, addr string, reusePort bool, listenerN, mtu int) error {
for i := 0; i < listenerN; i++ {
l, err := listen(network, addr, reusePort)
if err != nil {
return err
}
poller, err := netpoll.PollerInit()
if err != nil {
return err
}
loop := newEventLoop(s, l, poller, mtu)
s.loops[loop.l.fd] = loop
poller.Add(loop.l.fd, "r")
go loop.run(s.lockThread)
go loop.readLoop()
s.wg.Add(1)
}
return nil
}
func (svr *Server) Shutdown() {
if svr.closed.Load().(bool) {
return
}
loops := make(map[int]*eventLoop)
svr.Lock()
for fd, loop := range svr.loops {
loops[fd] = loop
}
svr.Unlock()
for _, loop := range loops {
if !loop.closed.Load().(bool) {
loop.Close(nil)
}
}
svr.wg.Wait()
svr.closed.Store(true)
}
func (svr *Server) eventLoopClosed(loop *eventLoop, err error) {
svr.Lock()
defer svr.Unlock()
delete(svr.loops, loop.l.fd)
svr.wg.Done()
if err != nil {
svr.handler.OnError(err)
}
}
// TODO: need load balancing?
func (svr *Server) WriteTo(data []byte, addr *net.UDPAddr) (int, error) {
if svr.closed.Load().(bool) {
return 0, fmt.Errorf("server closed")
}
var loop *eventLoop
svr.Lock()
for _, l := range svr.loops {
loop = l
break
}
svr.Unlock()
if loop == nil {
return 0, fmt.Errorf("not found valid event-loop")
}
return loop.writeTo(data, addr)
}