This repository has been archived by the owner on Jun 1, 2023. It is now read-only.
forked from Cistern/udpchan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudpchan.go
77 lines (66 loc) · 1.46 KB
/
udpchan.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
// Package udpchan provides a thin channel wrapper
// around UDP connections.
package udpchan
import (
"net"
)
// Usually the MTU is 1500 bytes and
// a little over 10k for jumbo frames.
// 10k should be plenty.
const mtu = 10000
// Connect dials to address and returns a send-only
// channel and an error.
func Connect(address string) (chan<- []byte, error) {
conn, err := net.Dial("udp", address)
if err != nil {
return nil, err
}
outbound := make(chan []byte, 10)
go func() {
defer func() {
if r := recover(); r != nil {
// Caught a panic, so we're going to close
// the outbound channel. Receivers are supposed
// to check for closed channels, so we're good.
close(outbound)
}
}()
for message := range outbound {
conn.Write(message)
}
}()
return outbound, nil
}
// Listen starts a UDP listener at address and
// returns a read-only channel and an error.
// If a value is sent to close, the UDP socket will
// be closed.
func Listen(address string, close chan bool) (<-chan []byte, error) {
udpAddr, err := net.ResolveUDPAddr("udp", address)
if err != nil {
return nil, err
}
conn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return nil, err
}
inbound := make(chan []byte, 10)
go func() {
for {
select {
case <-close:
conn.Close()
return
default:
}
b := make([]byte, mtu)
n, err := conn.Read(b)
if err != nil {
continue
}
b = b[:n]
inbound <- b
}
}()
return inbound, nil
}