-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
80 lines (67 loc) · 1.11 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
package fsync
import (
"context"
"io"
"log"
"net"
"sync"
)
type Server struct {
listener net.Listener
halt func()
wg sync.WaitGroup
}
func NewServer(addr string) *Server {
ctx, cancel := context.WithCancel(context.Background())
s := &Server{
halt: cancel,
}
l, err := net.Listen("tcp", addr)
if err != nil {
return nil
}
s.listener = l
s.wg.Add(1)
go s.serve(ctx)
return s
}
func (s *Server) Stop() {
s.halt()
s.listener.Close()
s.wg.Wait()
}
func (s *Server) serve(ctx context.Context) {
defer s.wg.Done()
for {
conn, err := s.listener.Accept()
if err != nil {
select {
case <-ctx.Done():
return
default:
log.Println("accept error", err)
continue
}
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
s.handleConection(conn)
}()
}
}
func (s *Server) handleConection(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 2048)
for {
n, err := conn.Read(buf)
if err != nil && err != io.EOF {
log.Println("read error", err)
return
}
if n == 0 {
return
}
log.Printf("received from %v: %s", conn.RemoteAddr(), string(buf[:n]))
}
}