-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
77 lines (65 loc) · 1.28 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
package main
import (
"bufio"
"flag"
"fmt"
"log"
"math/rand"
"os"
"time"
"golang.org/x/net/websocket"
)
type Message struct {
Text string `json:"text"`
}
var (
port = flag.String("port", "9123", "port used for ws connection")
)
func connect() (*websocket.Conn, error) {
return websocket.Dial(fmt.Sprintf("ws://localhost:%s", *port), "", mockedIP())
}
func mockedIP() string {
var arr [4]int
for i := 0; i < 4; i++ {
rand.Seed(time.Now().UnixNano())
arr[i] = rand.Intn(256)
}
return fmt.Sprintf("http://%d.%d.%d.%d", arr[0], arr[1], arr[2], arr[3])
}
func main() {
flag.Parse()
// connect
ws, err := connect()
if err != nil {
log.Fatal(err)
}
defer ws.Close()
// receive
var m Message
go func() {
for {
err := websocket.JSON.Receive(ws, &m)
if err != nil {
fmt.Println("Error receiving message: ", err.Error())
break
}
fmt.Println("Message: ", m)
}
}()
// send
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
text := scanner.Text()
if text == "" {
continue
}
m := Message{
Text: text,
}
err = websocket.JSON.Send(ws, m)
if err != nil {
fmt.Println("Error sending message: ", err.Error())
break
}
}
}