-
Notifications
You must be signed in to change notification settings - Fork 0
/
shutdown_tcp.go
81 lines (65 loc) · 1.09 KB
/
shutdown_tcp.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
package shutdown1
import (
"io"
"log"
"net"
"sync"
)
type Server struct {
listener net.Listener
quit chan interface{}
wg sync.WaitGroup
}
func NewServer(addr string) *Server {
s := &Server{quit: make(chan interface{})}
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
s.listener = l
s.wg.Add(1)
go s.serve()
return s
}
func (s *Server) Stop() {
close(s.quit)
s.listener.Close()
s.wg.Wait()
}
func (s *Server) serve() {
defer s.wg.Done()
for {
conn, err := s.listener.Accept()
if err != nil {
select {
case <-s.quit:
return
default:
log.Println("accept error:", err)
}
} else {
s.wg.Add(1)
go func() {
s.handlerConnection(conn)
s.wg.Done()
}()
}
}
}
func (s *Server) handlerConnection(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 2048)
for {
n, err := conn.Read(buf)
if err != nil && err != io.EOF {
log.Println()
}
if n == 0 {
return
}
log.Printf("recv from %v: %s", conn.RemoteAddr(), string(buf[:n]))
}
}
func init() {
log.SetFlags(log.Ltime | log.Lmicroseconds)
}