-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
86 lines (72 loc) · 1.69 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"./game"
"github.com/go-martini/martini"
"github.com/gorilla/websocket"
"html/template"
"net/http"
"strconv"
)
func httpHandler(w http.ResponseWriter, r *http.Request) {
data := struct {
Host string
MaxWidth int
MaxHeight int
Delay int
PlayerSpeed int
}{host + ":" + strconv.Itoa(port), game.MAX_WIDTH, game.MAX_HEIGHT,
int(DELAY.Nanoseconds() / 1000000), game.PLAYER_SPEED}
mainTemplate, err := template.ParseFiles("templates/main.html")
if err != nil {
w.Write([]byte(err.Error()))
return
}
err = mainTemplate.Execute(w, data)
if err != nil {
w.Write([]byte(err.Error()))
return
}
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func wsHandler(writer http.ResponseWriter, request *http.Request) {
conn, err := upgrader.Upgrade(writer, request, nil)
if err != nil {
return
}
readChannel := make(chan *MessageData, 100)
go ReadMessages(readChannel, conn, writer)
writeChannel := make(chan *GlobalState, 100)
go WriteMessages(writeChannel, conn)
AddController(readChannel, writeChannel)
}
func ReadMessages(c chan *MessageData, conn *websocket.Conn, writer http.ResponseWriter) {
for {
var data map[string]interface{}
err := conn.ReadJSON(&data)
if err != nil {
conn.Close()
close(c)
return
}
c <- NewMessageData(data)
}
}
func WriteMessages(c chan *GlobalState, conn *websocket.Conn) {
for msg := range c {
err := conn.WriteJSON(msg.ToJsonMap())
if err != nil {
conn.Close()
return
}
}
}
func startServer() {
m := martini.Classic()
m.Get("/", httpHandler)
m.Get("/ws", wsHandler)
m.Use(martini.Static(""))
m.RunOnAddr("0.0.0.0:" + strconv.Itoa(port))
}