-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
154 lines (128 loc) · 2.52 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
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
package gnet
import (
"github.com/MaxnSter/gnet/pool"
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/MaxnSter/GolangDataStructure/try"
"github.com/MaxnSter/gnet/util"
"github.com/golang/glog"
"github.com/pkg/errors"
)
type server struct {
net.Listener
Module
operator Operator
guard sync.Mutex
sessions map[uint64]NetSession
wg sync.WaitGroup
once sync.Once
done chan struct{}
}
func NewServer(l net.Listener, m Module, o Operator) NetServer {
s := &server{
Listener: l,
Module: m,
operator: o,
sessions: map[uint64]NetSession{},
done: make(chan struct{}),
}
return s
}
func (svc *server) Broadcast(f func(session NetSession)) {
svc.guard.Lock()
snapshot := svc.sessions
svc.guard.Unlock()
for _, s := range snapshot {
svc.Pool().Put(func() {
f(s)
}, pool.WithIdentify(s))
}
}
func (svc *server) GetSession(id uint64) (session NetSession, ok bool) {
svc.guard.Lock()
defer svc.guard.Unlock()
session, ok = svc.sessions[id]
return
}
func (svc *server) Run() {
svc.once.Do(func() {
go svc.signal()
svc.Module.Pool().Run()
svc.serve()
svc.wg.Wait()
svc.Module.Pool().Stop()
})
}
func (svc *server) signal() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)
signal.Ignore(syscall.SIGPIPE)
<-sigCh
svc.Stop()
}
func (svc *server) serve() {
try.Try(func() error {
var tempDelay time.Duration
for {
conn, err := svc.Accept()
if err != nil {
if err, ok := err.(net.Error); ok && err.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
time.Sleep(tempDelay)
continue
}
select {
case <-svc.done:
return nil
default:
}
return errors.Wrap(err, "accept failed")
}
go svc.onNewSession(conn)
}
}).Final(func(e error) error {
if e != nil {
glog.Errorf("%+v", e)
}
svc.Stop()
return nil
}).Do()
}
func (svc *server) onNewSession(conn net.Conn) {
id := util.GetUUID()
session := newSession(id, conn, svc, svc.operator)
svc.guard.Lock()
svc.sessions[id] = session
svc.guard.Unlock()
svc.wg.Add(1)
defer func() {
svc.guard.Lock()
delete(svc.sessions, id)
svc.guard.Unlock()
svc.wg.Done()
}()
session.Run()
}
func (svc *server) Stop() {
select {
case <-svc.done:
return
default:
}
close(svc.done)
svc.Listener.Close()
svc.Broadcast(func(session NetSession) {
session.Stop()
})
}