-
Notifications
You must be signed in to change notification settings - Fork 14
/
udp.go
45 lines (39 loc) · 1.06 KB
/
udp.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
package xnet
import (
"fmt"
"net"
)
// UDPSender is a Sender implementation that can write payload to the network
// address and reuses single system socket. It uses UDP packets to send data.
type UDPSender struct {
conn *net.UDPConn
}
// Send sends given payload to passed address. Data is sent using UDP packets.
// It returns number of bytes sent and error - if there was any.
func (s *UDPSender) Send(addr Address, payload []byte) (int, error) {
if s.conn == nil {
conn, err := net.ListenUDP("udp", nil)
if err != nil {
return 0, fmt.Errorf("could not create connection: %s", err)
}
s.conn = conn
}
udpAddr, err := net.ResolveUDPAddr("udp", string(addr))
if err != nil {
return 0, fmt.Errorf("invalid address %s: %s", addr, err)
}
n, err := s.conn.WriteTo(payload, udpAddr)
if err != nil {
return 0, fmt.Errorf("could not sent payload to %s: %s", addr, err)
}
return n, nil
}
// Release frees system socket used by sender.
func (s *UDPSender) Release() error {
if s.conn == nil {
return nil
}
err := s.conn.Close()
s.conn = nil
return err
}