/
client.go
139 lines (123 loc) · 2.37 KB
/
client.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package main
import (
"crypto/tls"
"fmt"
"golang.org/x/net/http2"
"io/ioutil"
"log"
"net"
"net/http"
"sync"
"time"
)
const HOST_IP = "localhost"
const HOST_PORT = "8080"
//const HOST_IP = "193.123.251.27"
const LIMIT = 1
func main() {
start := time.Now()
fmt.Println("start")
start = time.Now()
count2 := connectLongTime(HOST_PORT)
elapsed2 := time.Since(start)
fmt.Println("Connect with multiple goroutines:", count2, elapsed2)
time.Sleep(10 * time.Second)
value := GetValue(HOST_PORT)
fmt.Println("Get Value:", value)
fmt.Println("Connect with 1 goroutine:", elapsed2)
}
func connectAsyncWithLimit(port string) int {
count := 0
wg := sync.WaitGroup{}
wg.Add(LIMIT)
for i := 0; i < LIMIT; i++ {
go func() {
if load(port) == "hello" {
count += 1
}
wg.Done()
}()
}
wg.Wait()
return count
}
func connectAsyncDifferentAdd(port string) int {
count := 0
wg := sync.WaitGroup{}
for i := 0; i < LIMIT; i++ {
wg.Add(1)
go func() {
if load(port) == "hello" {
count += 1
}
wg.Done()
}()
}
wg.Wait()
return count
}
func connectAsyncWithoutWG(count int, port string) int {
for i := 0; i < LIMIT; i++ {
go func() {
if load(port) == "hello" {
count += 1
}
}()
}
return count
}
func connectLongTime(port string) int {
count := 0
for i := 0; i < LIMIT; i++ {
go func() {
if load(port) == "hello" {
count += 1
}
}()
}
return count
}
func load(port string) string {
client := &http.Client{Transport: &http2.Transport{
AllowHTTP: true,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
return net.Dial(network, addr)
},
},
}
res, err := client.Get("https://" + HOST_IP + ":" + port)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
return string(body)
}
func loadLong(port string) string {
res, err := http.Get("http://" + HOST_IP + ":" + port)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
time.Sleep(10 * time.Second)
return string(body)
}
func GetValue(port string) string {
res, err := http.Get("http://" + HOST_IP + ":" + port + "/value")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
return string(body)
}