-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathserver.go
127 lines (116 loc) · 2.36 KB
/
server.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
package main
import (
"errors"
"net"
"sync"
)
func NewServer() *server {
return &server{
readTimeoutSecond: 600,
writeTimeoutSecond: 30,
}
}
type server struct {
listener *net.TCPListener
mutex sync.Mutex
enableUDP bool
readTimeoutSecond uint //default 600
writeTimeoutSecond uint //default 30
headRequest *requestList
authHandle AuthHandle
onConnectedHandle OnConnectedHandle
onStartedHandle OnStartedHandle
}
func (s *server) SetAuthHandle(handle AuthHandle) {
s.authHandle = handle
}
func (s *server) EnableUDP() {
s.enableUDP = true
}
func (s *server) SetReadTimeOutSecond(second uint) {
s.readTimeoutSecond = second
}
func (s *server) SetWriteTimeOutSecond(second uint) {
s.writeTimeoutSecond = second
}
func (s *server) OnStarted(h OnStartedHandle) {
s.onStartedHandle = h
}
func (s *server) OnConnected(h OnConnectedHandle) {
s.onConnectedHandle = h
}
func (s *server) Close() error {
if s.listener == nil {
return errors.New("server is not running")
}
if err := s.listener.Close(); err != nil {
return err
} else {
return nil
}
}
func (s *server) Run(addr *net.TCPAddr) error {
var err error
s.listener, err = net.ListenTCP("tcp", addr)
if err != nil {
return err
}
if s.onStartedHandle != nil {
s.onStartedHandle(s.listener)
}
for {
conn, err := s.listener.AcceptTCP()
if err != nil {
break
}
go connHandle(conn, s)
}
s.listener = nil
s.closeRequests()
return nil
}
func (s *server) closeRequests() {
for s.headRequest != nil {
r := s.headRequest
s.removeRequestList(r)
_ = r.data.Close()
}
}
func connHandle(conn *net.TCPConn, s *server) {
r := &requestList{
prev: nil, next: nil,
data: Request{ClientConn: conn, server: s, tcpGram: TCPProtocol{
authHandle: s.authHandle,
}},
}
s.insertRequestList(r)
r.data.Process()
s.removeRequestList(r)
_ = r.data.Close()
}
func (s *server) insertRequestList(l *requestList) {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.headRequest != nil {
s.headRequest.prev = l
l.next = s.headRequest
s.headRequest = l
} else {
s.headRequest = l
}
}
func (s *server) removeRequestList(l *requestList) {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.headRequest == l {
s.headRequest = l.next
}
if l.prev != nil {
l.prev.next = l.next
l.prev = nil
}
if l.next != nil {
l.next.prev = l.prev
l.next = nil
}
}