2021-07-25 16:32:41 -04:00
|
|
|
package main
|
2021-07-22 15:37:25 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
|
2021-07-25 16:32:41 -04:00
|
|
|
"git.saintnet.tech/stryan/snengame/internal/coordinator"
|
2021-07-22 15:37:25 -04:00
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
var upgrader = websocket.Upgrader{} // use default options
|
|
|
|
|
2021-07-25 16:32:41 -04:00
|
|
|
func Serve(c *coordinator.Coordinator) {
|
2021-07-22 15:37:25 -04:00
|
|
|
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
|
2021-07-22 18:19:21 -04:00
|
|
|
serveWs(c, w, r)
|
2021-07-22 15:37:25 -04:00
|
|
|
})
|
|
|
|
err := http.ListenAndServe(":7636", nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("ListenAndServe: ", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-25 16:32:41 -04:00
|
|
|
func serveWs(c *coordinator.Coordinator, w http.ResponseWriter, r *http.Request) {
|
2021-07-22 15:37:25 -04:00
|
|
|
// Upgrade our raw HTTP connection to a websocket based one
|
|
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Print("Error during connection upgradation:", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
|
|
|
|
// The event loop
|
|
|
|
for {
|
2021-07-25 16:32:41 -04:00
|
|
|
var cmd coordinator.SessionCommand
|
2021-07-22 15:37:25 -04:00
|
|
|
err := conn.ReadJSON(&cmd)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Error during message reading:", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
log.Printf("Received: %s", cmd)
|
2021-07-22 18:19:21 -04:00
|
|
|
resp := c.Coordinate(&cmd)
|
2021-07-23 16:43:39 -04:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
log.Printf("sending: %v", resp)
|
2021-07-22 15:37:25 -04:00
|
|
|
err = conn.WriteJSON(resp)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Error during message writing:", err)
|
|
|
|
break
|
|
|
|
}
|
2021-07-25 16:32:41 -04:00
|
|
|
if resp.Result == coordinator.SessionRespLeft {
|
2021-07-22 18:19:21 -04:00
|
|
|
break
|
|
|
|
}
|
2021-07-22 15:37:25 -04:00
|
|
|
}
|
|
|
|
}
|