-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
84 lines (66 loc) · 2.22 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
/* Entry point for COAP echo server running over UDP.
*
* This code based on the UDP echo server code also in this repo
* and on the examples here:
* https://github.com/dustin/go-coap
*
* A COAP confirmable message will be picked up by this server
* and confirmed to the recipient along with the content received.
*/
package main
import (
"net"
"fmt"
"os"
"flag"
"log"
"github.com/dustin/go-coap"
)
//--------------------------------------------------------------------
// Types
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Variables
//--------------------------------------------------------------------
var numPackets int
// Command-line flags
var pPort = flag.String ("p", "5683", "the UDP port to listen on.")
var Usage = func() {
fmt.Fprintf(os.Stderr, "\n%s: run the COAP echo server. Usage:\n", os.Args[0])
flag.PrintDefaults()
}
//--------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------
func coapHandler (l *net.UDPConn, pAddress *net.UDPAddr, pMessage *coap.Message) *coap.Message {
var pResponse *coap.Message
numPackets++;
log.Printf("%d: %v <-> %v: %#v", numPackets, pAddress, pMessage.Path(), pMessage)
if pMessage.IsConfirmable() {
pResponse = &coap.Message{
Type: coap.Acknowledgement,
Code: coap.Content,
MessageID: pMessage.MessageID,
Token: pMessage.Token,
Payload: pMessage.Payload,
}
pResponse.SetOption(coap.ContentFormat, coap.TextPlain)
log.Printf("Transmitting %#v", pResponse)
}
return pResponse
}
// Entry point
func main() {
// Deal with the command-line parameters
flag.Parse()
// Set up logging
log.SetFlags(log.LstdFlags)
// Say what we're doing
fmt.Printf("Echoing COAP confirmable messages received on port %s.\n", *pPort)
// Run the server
err := coap.ListenAndServe("udp", ":" + *pPort, coap.FuncHandler(coapHandler))
if err != nil {
fmt.Printf("Couldn't start COAP echo server on port %s (%s).\n", *pPort, err.Error())
}
}
// End Of File