-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
72 lines (62 loc) · 1.71 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
package main
import (
"flag"
"fmt"
"io"
"log"
"net/url"
"os"
"time"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
var (
ip = flag.String("ip", "127.0.0.1", "server IP")
connections = flag.Int("conn", 1, "number of websocket connections")
)
func main() {
flag.Usage = func() {
io.WriteString(os.Stderr, `Websockets client generator Example usage: ./client -ip=172.17.0.1 -conn=10`)
flag.PrintDefaults()
}
flag.Parse()
u := url.URL{Scheme: "ws", Host: *ip + ":10080", Path: "/"}
log.Printf("Connecting to %s", u.String())
var conns []*websocket.Conn
for i := 0; i < *connections; i++ {
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
fmt.Println("Failed to connect", i, err)
break
}
conns = append(conns, c)
defer func() {
c.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second))
time.Sleep(time.Second)
c.Close()
}()
}
log.Printf("Finished initializing %d connections", len(conns))
tts := time.Second
if *connections > 50 {
tts = time.Millisecond * 5
}
sendEvent := cloudevents.NewEvent()
sendEvent.SetID(uuid.NewString())
sendEvent.SetSource("client")
sendEvent.SetType("hello")
data := []byte(`{"message":"hello world"}`)
sendEvent.SetData(cloudevents.ApplicationJSON, data)
for {
for i := 0; i < len(conns); i++ {
time.Sleep(tts)
conn := conns[i]
log.Printf("Conn %d sending message", i)
if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(time.Second*5)); err != nil {
fmt.Printf("Failed to receive pong: %v", err)
}
_ = conn.WriteJSON(sendEvent)
}
}
}