forked from lithdew/reliable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (70 loc) · 1.72 KB
/
main.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"bytes"
"errors"
"flag"
"io"
"log"
"net"
"sync/atomic"
"time"
"github.com/TheSmallBoat/reliable"
)
var (
listener bool
)
func check(err error) {
if err != nil && !errors.Is(err, io.EOF) {
log.Panic(err)
}
}
func listen(addr string) net.PacketConn {
conn, err := net.ListenPacket("udp", addr)
check(err)
log.Printf("%s: Listening for peers.", conn.LocalAddr())
return conn
}
func main() {
flag.BoolVar(&listener, "l", false, "either listen or dial")
flag.Parse()
host := flag.Arg(0)
if !listener || host == "" {
host = ":0"
}
conn := listen(host)
counter := uint64(0)
handler := func(buf []byte, addr net.Addr) {
if len(buf) == 0 {
return
}
//log.Printf("%s->%s: (seq=%d) (size=%d)", addr.String(), conn.LocalAddr().String(), seq, len(buf))
atomic.AddUint64(&counter, 1)
}
endpoint := reliable.NewEndpoint(conn, reliable.WithEndpointPacketHandler(handler))
go endpoint.Listen()
defer func() {
check(endpoint.Close())
check(conn.Close())
}()
if listener {
for range time.Tick(1 * time.Second) {
numPackets := atomic.SwapUint64(&counter, 0)
numBytes := float64(numPackets) * 1400.0 / 1024.0 / 1024.0
log.Printf("%s: Received %d packets (%.2f MiB).", conn.LocalAddr(), numPackets, numBytes)
}
}
addr, err := net.ResolveUDPAddr("udp", flag.Arg(0))
check(err)
data := bytes.Repeat([]byte("x"), 1400)
go func() {
for range time.Tick(1 * time.Second) {
numPackets := atomic.SwapUint64(&counter, 0)
numBytes := float64(numPackets) * 1400.0 / 1024.0 / 1024.0
log.Printf("%s: Sent %d packets (%.2f MiB).", conn.LocalAddr(), numPackets, numBytes)
}
}()
for {
check(endpoint.WriteReliablePacket(data, addr))
atomic.AddUint64(&counter, 1)
}
}