/
grid.go
76 lines (58 loc) · 1.55 KB
/
grid.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
package main
import (
"container/list"
"fmt"
"log"
"net/http"
"regexp"
"code.google.com/p/go.net/websocket"
)
const listenAddr = ":4000"
func main() {
http.HandleFunc("/", rootHandler)
http.Handle("/socket", websocket.Handler(socketHandler))
err := http.ListenAndServe(listenAddr, nil)
if err != nil {
log.Fatal(err)
}
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
}
// type subscriberQueue chan []byte
// var subscriberQueues = make([](chan *websocket.Conn), 100)
var clients = list.New()
// type subscriber chan []byte
// var subscribers = make([]subscriber, 100)
func socketHandler(ws *websocket.Conn) {
fmt.Printf("readWriteServer %#v\n", ws.Config())
clientListEl := clients.PushBack(ws)
for {
buf := make([]byte, 100)
n, err := ws.Read(buf)
if err != nil {
fmt.Println(err)
break
}
go handleMessage(buf[:n], ws)
}
clients.Remove(clientListEl)
fmt.Println("readWriteServer finished")
}
var updateRegExp, _ = regexp.Compile("^UPDATE\\:([0-9]+)\\,([0-9]+)\\:(.)$")
func handleMessage(message []byte, origin *websocket.Conn) {
fmt.Printf("recv:%q\n", message)
submatches := updateRegExp.FindSubmatch(message)
if submatches != nil {
fmt.Printf("x: %q\n", submatches[1])
fmt.Printf("y: %q\n", submatches[2])
fmt.Printf("char: %q\n", submatches[3])
}
for e := clients.Front(); e != nil; e = e.Next() {
// do something with e.Value
conn := e.Value.(*websocket.Conn)
// if conn != origin {
websocket.Message.Send(conn, fmt.Sprintf("%s", message))
// }
}
}