-
Notifications
You must be signed in to change notification settings - Fork 103
/
client.go
66 lines (55 loc) · 1.18 KB
/
client.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
package coap
import (
"net"
"time"
)
const (
// ResponseTimeout is the amount of time to wait for a
// response.
ResponseTimeout = time.Second * 2
// ResponseRandomFactor is a multiplier for response backoff.
ResponseRandomFactor = 1.5
// MaxRetransmit is the maximum number of times a message will
// be retransmitted.
MaxRetransmit = 4
)
// Conn is a CoAP client connection.
type Conn struct {
conn *net.UDPConn
buf []byte
}
// Dial connects a CoAP client.
func Dial(n, addr string) (*Conn, error) {
uaddr, err := net.ResolveUDPAddr(n, addr)
if err != nil {
return nil, err
}
s, err := net.DialUDP("udp", nil, uaddr)
if err != nil {
return nil, err
}
return &Conn{s, make([]byte, maxPktLen)}, nil
}
// Send a message. Get a response if there is one.
func (c *Conn) Send(req Message) (*Message, error) {
err := Transmit(c.conn, nil, req)
if err != nil {
return nil, err
}
if !req.IsConfirmable() {
return nil, nil
}
rv, err := Receive(c.conn, c.buf)
if err != nil {
return nil, err
}
return &rv, nil
}
// Receive a message.
func (c *Conn) Receive() (*Message, error) {
rv, err := Receive(c.conn, c.buf)
if err != nil {
return nil, err
}
return &rv, nil
}