-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
88 lines (72 loc) · 1.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
package socketer
import (
"bufio"
"io"
"net"
)
type Server struct {
listener net.Listener
address string
network string
closeListener CloseListener
receiveListener ReceiveListener
connectListener ConnectListener
}
func NewServer(network, address string) *Server {
return &Server{
network: network,
address: address,
}
}
func (s *Server) OnConnect(l ConnectListener) {
s.connectListener = l
}
func (s *Server) OnReceive(l ReceiveListener) {
s.receiveListener = l
}
func (s *Server) OnClose(l CloseListener) {
s.closeListener = l
}
func (s *Server) Send(conn net.Conn, data []byte) (int, error) {
return conn.Write(data)
}
func (s *Server) Close(conn net.Conn) error {
err := conn.Close()
if s.closeListener != nil {
s.connectListener(conn)
}
return err
}
func (s *Server) Listen() error {
var err error
s.listener, err = net.Listen(s.network, s.address)
if err != nil {
return err
}
for {
conn, err := s.listener.Accept()
if err != nil {
continue
}
if s.connectListener != nil {
s.connectListener(conn)
}
go s.accept(conn)
}
}
func (s *Server) accept(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
s.Close(conn)
}
break
}
if s.receiveListener != nil {
go s.receiveListener(message, conn)
}
}
}