-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
70 lines (60 loc) · 1.15 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
package main
import (
"bufio"
"flag"
"fmt"
"golang.org/x/net/websocket"
"log"
"net/http"
"os"
"strconv"
)
var (
IS_SERVER = flag.Bool("server", false, "Run as the echo server")
PORT = flag.Int("port", 5000, "What port should/is the the server run(ning) on?")
)
func main() {
flag.Parse()
if *IS_SERVER {
server()
} else {
client()
}
}
func EchoServer(ws *websocket.Conn) {
for {
var data interface{}
err := websocket.JSON.Receive(ws, &data)
if err != nil {
log.Println(err)
return
}
log.Println("data: ", data)
websocket.JSON.Send(ws, data)
}
}
func server() {
http.Handle("/ws", websocket.Handler(EchoServer))
err := http.ListenAndServe(":"+strconv.Itoa(*PORT), nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
func client() {
ws, err := websocket.Dial("ws://localhost:"+strconv.Itoa(*PORT)+"/ws", "", "http://localhost/")
if err != nil {
log.Fatalln(err)
}
bio := bufio.NewScanner(os.Stdin)
go func() {
for {
var data interface{}
websocket.JSON.Receive(ws, &data)
fmt.Println("Server:", data)
}
}()
for bio.Scan() {
line := bio.Text()
websocket.JSON.Send(ws, line)
}
}