-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathxserver.go
199 lines (168 loc) · 3.83 KB
/
xserver.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package xtcp
import (
"net"
"sync"
"time"
)
// Server used for running a tcp server.
type Server struct {
Opts *Options
stopped chan struct{}
wg sync.WaitGroup
mu sync.Mutex
once sync.Once
lis net.Listener
conns map[*Conn]bool
}
// ListenAndServe listens on the TCP network address addr and then
// calls Serve to handle requests on incoming connections.
func (s *Server) ListenAndServe(addr string) error {
l, err := net.Listen("tcp", addr)
if err != nil {
return err
}
s.Serve(l)
return nil
}
// Serve start the tcp server to accept.
func (s *Server) Serve(l net.Listener) {
defer s.wg.Done()
s.wg.Add(1)
s.mu.Lock()
s.lis = l
s.mu.Unlock()
logger.Log(Info, "XTCP - Server listen on: ", l.Addr().String())
var tempDelay time.Duration // how long to sleep on accept failure
maxDelay := 1 * time.Second
for {
conn, err := l.Accept()
if err != nil {
if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if tempDelay > maxDelay {
tempDelay = maxDelay
}
logger.Logf(Error, "XTCP - Server Accept error: %v; retrying in %v", err, tempDelay)
select {
case <-time.After(tempDelay):
continue
case <-s.stopped:
return
}
}
if !s.IsStopped() {
logger.Logf(Error, "XTCP - Server Accept error: %v; server closed!", err)
s.Stop(StopImmediately)
}
return
}
tempDelay = 0
go s.handleRawConn(conn)
}
}
// IsStopped check if server is stopped.
func (s *Server) IsStopped() bool {
select {
case <-s.stopped:
return true
default:
return false
}
}
// Stop stops the tcp server.
// StopImmediately: immediately closes all open connections and listener.
// StopGracefullyButNotWait: stops the server and stop all connections gracefully.
// StopGracefullyAndWait: stops the server and blocks until all connections are stopped gracefully.
func (s *Server) Stop(mode StopMode) {
s.once.Do(func() {
close(s.stopped)
s.mu.Lock()
lis := s.lis
s.lis = nil
conns := s.conns
s.conns = nil
s.mu.Unlock()
if lis != nil {
lis.Close()
}
m := mode
if m == StopGracefullyAndWait {
// don't wait each conn stop.
m = StopGracefullyButNotWait
}
for c := range conns {
c.Stop(m)
}
if mode == StopGracefullyAndWait {
s.wg.Wait()
}
logger.Log(Info, "XTCP - Server stopped.")
})
}
func (s *Server) handleRawConn(conn net.Conn) {
s.mu.Lock()
if s.conns == nil { // s.conns == nil mean server stopped
s.mu.Unlock()
conn.Close()
return
}
s.mu.Unlock()
tcpConn := NewConn(s.Opts)
tcpConn.RawConn = conn
if !s.addConn(tcpConn) {
tcpConn.Stop(StopImmediately)
return
}
s.wg.Add(1)
defer func() {
s.removeConn(tcpConn)
s.wg.Done()
}()
s.Opts.Handler.OnAccept(tcpConn)
tcpConn.serve()
}
func (s *Server) addConn(conn *Conn) bool {
s.mu.Lock()
if s.conns == nil {
s.mu.Unlock()
return false
}
s.conns[conn] = true
s.mu.Unlock()
return true
}
func (s *Server) removeConn(conn *Conn) {
s.mu.Lock()
if s.conns != nil {
delete(s.conns, conn)
}
s.mu.Unlock()
}
// CurClientCount return current client count.
func (s *Server) CurClientCount() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.conns)
}
// NewServer create a tcp server but not start to accept.
// The opts will set to all accept conns.
func NewServer(opts *Options) *Server {
if opts.RecvBufSize <= 0 {
logger.Logf(Warn, "Invalid Opts.RecvBufSize : %v, use DefaultRecvBufSize instead", opts.RecvBufSize)
opts.RecvBufSize = DefaultRecvBufSize
}
if opts.SendBufListLen <= 0 {
logger.Logf(Warn, "Invalid Opts.SendBufListLen : %v, use DefaultSendBufListLen instead", opts.SendBufListLen)
opts.SendBufListLen = DefaultSendBufListLen
}
s := &Server{
Opts: opts,
stopped: make(chan struct{}),
conns: make(map[*Conn]bool),
}
return s
}