-
Notifications
You must be signed in to change notification settings - Fork 9
/
udp_conn.go
55 lines (48 loc) · 1.08 KB
/
udp_conn.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
package nighthawk
import (
"fmt"
"log"
"net"
)
type updHandler func(b []byte, size int, addr *net.Addr)
type udpListener struct {
port int
netLn *net.UDPConn
}
var portNum = 4300
//creates a udp listener struct
func createUDPListener() *udpListener {
ln := udpListener{port: portNum} //we will switch out to port recycle thing
portNum++
return &ln
}
//starts the listener and sets up the processing closure
func (c *udpListener) start(handler updHandler) error {
sAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", c.port))
if err != nil {
log.Println("error binding UDP listener:", err)
return err
}
ln, err := net.ListenUDP("udp", sAddr)
c.netLn = ln
if err != nil {
log.Println("error starting UDP listener:", err)
return err
}
defer c.netLn.Close()
for {
buf := make([]byte, 1024)
n, addr, err := c.netLn.ReadFrom(buf)
if err != nil {
log.Println("error reading from UDP listener:", err)
}
handler(buf, n, &addr)
}
return nil
}
//stops the listener because we are done with it
func (c *udpListener) stop() {
if c.netLn != nil {
c.netLn.Close()
}
}