/
main.go
95 lines (75 loc) · 1.35 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"flag"
"fmt"
"net/http"
"os"
"sync"
"github.com/golang/glog"
"golang.org/x/net/websocket"
)
const (
indexPath = "/"
wsPath = "/ws"
port = 8080
)
var (
exitStatus int
usrCnt int
// user count mutex
ucm = new(sync.Mutex)
)
type data struct {
Cmd string `json:"cmd"`
Time int `json:"time"`
}
func init() {
flag.Parse()
}
func main() {
run()
os.Exit(exitStatus)
}
func run() {
glog.Info("run()")
http.Handle(indexPath, http.FileServer(http.Dir("client")))
http.HandleFunc(wsPath,
func(w http.ResponseWriter, req *http.Request) {
s := websocket.Server{Handler: websocket.Handler(handler)}
s.ServeHTTP(w, req)
})
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
if err != nil {
glog.Error(err)
exitStatus = 1
}
}
func handler(conn *websocket.Conn) {
userID := getUserID()
glog.Info("start: ", userID)
for {
var d data
glog.Info("wait receive")
rErr := websocket.JSON.Receive(conn, &d)
if rErr != nil {
glog.Error("receive error: ", rErr)
break
}
glog.Info("receive data:", d)
// send data
d.Cmd = "pong"
glog.Info("send data:", d)
sErr := websocket.JSON.Send(conn, d)
if sErr != nil {
glog.Error("send error: ", sErr)
break
}
}
glog.Info("end: ", userID)
}
func getUserID() int {
ucm.Lock()
defer ucm.Unlock()
usrCnt++
return usrCnt
}