package main
import ( //导入相应的包
"log"
"net"
"github.com/dustin/go-coap"
)
func handleA(l *net.UDPConn, a *net.UDPAddr, m *coap.Message) *coap.Message {
log.Printf("Got message in handleA: path=%q: %#v from %v", m.Path(), m, a)
if m.IsConfirmable() {
res := &coap.Message{
Type: coap.Acknowledgement,
Code: coap.Content,
MessageID: m.MessageID,
Token: m.Token,
Payload: []byte("hello to you!"),
}
res.SetOption(coap.ContentFormat, coap.TextPlain)
log.Printf("Transmitting from A %#v", res)
return res
}
return nil
}
func handleB(l *net.UDPConn, a *net.UDPAddr, m *coap.Message) *coap.Message {
log.Printf("Got message in handleB: path=%q: %#v from %v", m.Path(), m, a)
if m.IsConfirmable() { //判断是否为CON数据
res := &coap.Message{
Type: coap.Acknowledgement, //指定回复数据为ACK类型
Code: coap.Content,
MessageID: m.MessageID,
Token: m.Token,
Payload: []byte("good bye!"),
}
res.SetOption(coap.ContentFormat, coap.TextPlain) //设置Option ContentFormat
log.Printf("Transmitting from B %#v", res)
return res
}
return nil
}
func main() {
mux := coap.NewServeMux()
mux.Handle("/a", coap.FuncHandler(handleA)) //创建 "/a"处理接口
mux.Handle("/b", coap.FuncHandler(handleB)) //创建 "/b"处理接口
log.Fatal(coap.ListenAndServe("udp", ":5683", mux)) //启动Server 端口为5683 这里为什么要用":5683"?搞不明白
}
开源Go版 CoAP实现分析 - example/server.go
猜你喜欢
转载自blog.csdn.net/lx121451/article/details/91896538
今日推荐
周排行