-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
70 lines (61 loc) · 1.43 KB
/
server.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 (
"encoding/json"
"github.com/gorilla/websocket"
"log"
"net/http"
)
var upgrader = websocket.Upgrader{} // use default websocket options
// Data to stream to clients
type ClientData struct {
Id int // node (player) id
Color string // node color
}
func handler(w http.ResponseWriter, r *http.Request) {
log.Print(r.Host, " connected (ws)")
// upgrade the http connection to a websocket
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
// starts the simulation once the connection is established (few lines back)
go sl.startSimulation()
defer c.Close()
// send some messages to the client
for {
data := <- colorChange
buf, _ := json.Marshal(data)
err = c.WriteMessage(websocket.TextMessage, buf)
if err != nil {
log.Println("write:", err)
break
}
}
// Echo client messages (write what we read)
/*for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
log.Println("write:", err)
break
}
}*/
}
func serveHome(w http.ResponseWriter, r *http.Request) {
log.Print(r.Host, " connected")
if r.URL.Path != "/" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
http.ServeFile(w, r, "index.html")
}