-
Notifications
You must be signed in to change notification settings - Fork 0
/
udp_server.go
87 lines (75 loc) · 1.6 KB
/
udp_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
package castcenter
import (
"net"
"time"
)
const (
datagramChannelBufferSize = 4 * 1024
datagramReadBufferSize = 4 * 1024
)
// Handler .
type Handler func(*UDPEvent)
// UDPServer .
type UDPServer struct {
handler Handler
ch chan *UDPEvent
connection *net.UDPConn
}
// UDPEvent .
type UDPEvent struct {
ip string
buf []byte
}
// NewUDPServer returns a new UDPServer
func NewUDPServer(handler Handler, chanSize int) *UDPServer {
return &UDPServer{
handler: handler,
ch: make(chan *UDPEvent, chanSize),
}
}
// ListenUDP Configure the UDPServer for listen on an UDP addr
func (s *UDPServer) ListenUDP(conn *net.UDPConn) error {
s.connection = conn
conn.SetReadBuffer(datagramReadBufferSize)
go recoverLoop(s.receiveDatagrams)
recoverLoop(s.parseDatagrams)
return nil
}
func (s *UDPServer) receiveDatagrams() {
for {
buf := GetBytes()
n, addr, err := s.connection.ReadFromUDP(buf)
if err == nil {
if n > 0 {
s.ch <- &UDPEvent{
ip: addr.IP.String(),
buf: buf[:n],
}
}
} else {
// there has been an error. Either the UDPServer has been killed
// or may be getting a transitory error due to (e.g.) the
// interface being shutdown in which case sleep() to avoid busy wait.
opError, ok := err.(*net.OpError)
if (ok) && !opError.Temporary() && !opError.Timeout() {
return
}
time.Sleep(10 * time.Millisecond)
}
}
}
func (s *UDPServer) parseDatagrams() {
for {
select {
case msg, ok := <-s.ch:
if !ok {
return
}
s.handle(msg)
}
}
}
func (s *UDPServer) handle(msg *UDPEvent) {
defer PutBytes(msg.buf)
s.handler(msg)
}