-
Notifications
You must be signed in to change notification settings - Fork 148
/
udp.go
56 lines (45 loc) · 1.03 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
46
47
48
49
50
51
52
53
54
55
56
package messagereader
import (
"fmt"
"net"
"github.com/cloudfoundry/sonde-go/events"
"github.com/gogo/protobuf/proto"
)
type UDPReader struct {
port int
connection *net.UDPConn
}
func NewUDP(port int) *UDPReader {
udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", port))
if err != nil {
panic(err)
}
connection, err := net.ListenUDP("udp", udpAddr)
if err != nil {
panic(err)
}
return &UDPReader{
port: port,
connection: connection,
}
}
func (reader *UDPReader) Read() *events.Envelope {
readBuffer := make([]byte, 65535)
count, _, err := reader.connection.ReadFrom(readBuffer)
if err != nil {
fmt.Printf("Error reading from UDP connection: %s", err.Error())
return nil
}
readData := make([]byte, count)
copy(readData, readBuffer[:count])
var message events.Envelope
err = proto.Unmarshal(readData[32:], &message)
if err != nil {
fmt.Printf("Error unmarshalling data: %s \n", err.Error())
return nil
}
return &message
}
func (reader *UDPReader) Close() {
reader.connection.Close()
}