forked from dustin/go-coap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
148 lines (126 loc) · 3.16 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// Package coap provides a CoAP client and server.
package coap
import (
"fmt"
"log"
"net"
"time"
)
const maxPktLen = 1500
// Handler is a type that handles CoAP messages.
type Handler interface {
// Handle the message and optionally return a response message.
ServeCOAP(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message
}
type funcHandler func(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message
func (f funcHandler) ServeCOAP(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message {
return f(l, a, m)
}
// FuncHandler builds a handler from a function.
func FuncHandler(f func(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message) Handler {
return funcHandler(f)
}
func handlePacket(l *net.UDPConn, data []byte, u *net.UDPAddr,
rh Handler) {
defer func() {
data = nil
// recover panic
if err := recover(); err != nil {
if debugEnable {
TraceError("[coap] handle packet panic: %s", err)
}
}
}()
if debugEnable {
tracePrintOut := true
// health monitor for aliyun
// Request: RUOK
// do not print out log for health monitor
if healthMonitorEnable {
if len(data) == 4 {
if data[0] == 'R' && data[1] == 'U' && data[2] == 'O' && data[3] == 'K' {
tracePrintOut = false
}
}
}
if tracePrintOut {
TraceInfo("[coap] Remote: %v, Recv: %d, Bytes: %s", u, len(data), fmt.Sprintf("% X", data))
}
}
// health monitor for aliyun
// Request: RUOK
// Response: IMOK
if healthMonitorEnable {
if len(data) == 4 {
if data[0] == 'R' && data[1] == 'U' && data[2] == 'O' && data[3] == 'K' {
// Response IMOK
l.WriteToUDP([]byte("IMOK"), u)
return
}
}
}
msg, err := ParseMessage(data)
if err != nil {
log.Printf("Error parsing %v", err)
return
}
rv := rh.ServeCOAP(l, u, &msg)
if rv != nil {
Transmit(l, u, *rv)
}
}
// Transmit a message.
func Transmit(l *net.UDPConn, a *net.UDPAddr, m Message) error {
d, err := m.MarshalBinary()
if err != nil {
return err
}
if a == nil {
_, err = l.Write(d)
} else {
_, err = l.WriteTo(d, a)
}
return err
}
// Receive a message.
func Receive(l *net.UDPConn, buf []byte) (Message, error) {
l.SetReadDeadline(time.Now().Add(ResponseTimeout))
nr, _, err := l.ReadFromUDP(buf)
if err != nil {
return Message{}, err
}
return ParseMessage(buf[:nr])
}
// ListenAndServe binds to the given address and serve requests forever.
func ListenAndServe(n, addr string, rh Handler) error {
uaddr, err := net.ResolveUDPAddr(n, addr)
if err != nil {
return err
}
l, err := net.ListenUDP(n, uaddr)
if err != nil {
return err
}
return Serve(l, rh)
}
// Serve processes incoming UDP packets on the given listener, and processes
// these requests forever (or until the listener is closed).
func Serve(listener *net.UDPConn, rh Handler) error {
buf := make([]byte, maxPktLen)
for {
nr, addr, err := listener.ReadFromUDP(buf)
if err != nil {
if neterr, ok := err.(net.Error); ok && (neterr.Temporary() || neterr.Timeout()) {
time.Sleep(5 * time.Millisecond)
continue
}
if debugEnable {
TraceInfo("[coap] Serve ReadFromUDP error: %s", err)
}
continue
}
tmp := make([]byte, nr)
copy(tmp, buf)
go handlePacket(listener, tmp, addr, rh)
}
}