-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathclient.go
66 lines (56 loc) · 1.51 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
package main
import (
"fmt"
"os"
"strings"
"time"
"github.com/gorilla/websocket"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "Missing URL\n")
os.Exit(1)
}
url := os.Args[1]
// Make sure the URL is a websocket URL
if !strings.HasPrefix(url, "ws://") && !strings.HasPrefix(url, "wss://") {
fmt.Printf("URL (%s) must be ws://... or wss:/...", url)
os.Exit(1)
}
// Establish the websocket connection
c, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
fmt.Printf("Error connecting to %s: %s\n", url, err)
os.Exit(1)
}
defer c.Close()
// The string we'll send, and what we expect to get back.
// The server should just reverse the string.
buf := []byte("1234567890")
expected := "0987654321"
// How many messages we'll send and receive
tries := 10
go func() {
// Loop until we get all "tried" number of messages from server
for count := 0; count < tries; count++ {
if _, message, err := c.ReadMessage(); err != nil {
fmt.Printf("Read error: %s\n", err)
os.Exit(1)
} else if string(message) != expected {
fmt.Printf("Unexpected output: %q\n", message)
os.Exit(1)
} else {
fmt.Printf("Client read: %q\n", message)
}
}
}()
// Send "tries" number of messages to the server
for i := 0; i < tries; i++ {
if err := c.WriteMessage(websocket.TextMessage, buf); err != nil {
fmt.Printf("Write error: %s\n", err)
os.Exit(1)
}
fmt.Printf("Client write: %q\n", string(buf))
time.Sleep(2 * time.Second) // wait to read response
}
}