forked from nu7hatch/gonetbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
124 lines (111 loc) · 1.91 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"flag"
"fmt"
"net"
"time"
"sync"
"os"
"os/signal"
)
var (
Addr string
Cmd string
Num uint
Size uint
wg sync.WaitGroup
quit chan bool
sc chan bool // sent packets
lc chan bool // lost packets
ac chan bool // acctive connections
pc chan bool // pending connections
ec chan bool // error connections
pack []byte
)
func init() {
flag.UintVar(&Num, "n", 10, "number of concurrent clients")
flag.UintVar(&Size, "s", 1, "packet size (in bytes)")
flag.Parse()
Addr = flag.Arg(0)
if Addr == "" {
usage()
os.Exit(1)
}
}
func usage() {
fmt.Fprintf(os.Stderr, "Usage: time %s [options] addr cmd\n", os.Args[0])
flag.PrintDefaults()
}
func status() {
wg.Add(1)
defer wg.Done()
acs, ecs, pcs, scs, lcs := 0, 0, 0, 0, 0
fmt.Printf("Benchmarking %s with %d concurrent connections:\n\n", Addr, Num)
for {
select {
case <-ac:
acs += 1
pcs -= 1
case <-ec:
ecs += 1
pcs -= 1
case <-pc:
pcs += 1
case <-sc:
scs += 1
case <-lc:
lcs += 1
case <-quit:
fmt.Println("")
return
}
fmt.Printf("\rConnections (active: %d, pending: %d, failed: %d), Packets (sent: %d, lost: %d)", acs, pcs, ecs, scs, lcs)
}
}
func read(conn net.Conn) {
for {
buf := make([]byte, 1024)
conn.Read(buf)
}
}
func client() {
conn, err := net.Dial("tcp", Addr)
if err != nil {
ec <- true
return
}
ac <- true
defer conn.Close()
go read(conn)
for {
n, err := conn.Write(pack)
if err != nil || n != len(pack) {
lc <- true
}
sc <- true
<-time.After(1 * time.Second)
}
}
func startAll() {
for i := 0; i < int(Num); i += 1 {
pc <- true
go client()
}
}
func main() {
quit = make(chan bool)
ac = make(chan bool)
sc = make(chan bool)
pc = make(chan bool)
ec = make(chan bool)
lc = make(chan bool)
pack = make([]byte, Size)
for i, _ := range pack {
pack[i] = 'x'
}
go status()
go startAll()
<-signal.Incoming
quit <- true
wg.Wait()
}