-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
57 lines (49 loc) · 1.33 KB
/
server.go
File metadata and controls
57 lines (49 loc) · 1.33 KB
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
package dagger
import "sync"
import "net"
import "time"
// Server ...
type Server struct {
protocol Protocol // custom packet protocol
callback SessionCallback // custom server callback
exitChan chan struct{} // notify all goroutines to close
waitGroup *sync.WaitGroup // wait for all goroutines
packetSendSize uint32 // session's packet send channel size
packetRecvSize uint32 // session's packet receive channel size
}
// NewServer inits a new server instance
func NewServer(callback SessionCallback, protocol Protocol, packetSendSize uint32, packetRecvSize uint32) *Server {
return &Server{
protocol: protocol,
callback: callback,
exitChan: make(chan struct{}),
waitGroup: &sync.WaitGroup{},
packetSendSize: packetSendSize,
packetRecvSize: packetRecvSize,
}
}
// Serve is a Server run method
func (server *Server) Serve(listener *net.TCPListener, timeout time.Duration) {
server.waitGroup.Add(1)
defer func() {
listener.Close()
server.waitGroup.Done()
}()
for {
select {
case <-server.exitChan:
return
default:
}
listener.SetDeadline(time.Now().Add(timeout))
conn, err := listener.AcceptTCP()
if err != nil {
continue
}
server.waitGroup.Add(1)
go func() {
newSession(conn, server).Work()
server.waitGroup.Done()
}()
}
}