64 lines
1.5 KiB
Go
64 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.saintnet.tech/stryan/snengame/internal/coordinator"
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
var upgrader = websocket.Upgrader{} // use default options
|
|
|
|
func Serve(c *coordinator.Coordinator) {
|
|
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
|
|
serveWs(c, w, r)
|
|
})
|
|
log.Println("starting websocket")
|
|
err := http.ListenAndServe(":7636", nil)
|
|
if err != nil {
|
|
log.Fatal("ListenAndServe: ", err)
|
|
}
|
|
}
|
|
|
|
func serveWs(c *coordinator.Coordinator, w http.ResponseWriter, r *http.Request) {
|
|
// Upgrade our raw HTTP connection to a websocket based one
|
|
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
|
|
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 {
|
|
var cmd coordinator.SessionCommand
|
|
err := conn.ReadJSON(&cmd)
|
|
if err != nil {
|
|
log.Println("Error during message reading:", err)
|
|
break
|
|
}
|
|
if cmd.Command != coordinator.SessionCmdPoll {
|
|
log.Printf("Received: %s", cmd)
|
|
}
|
|
resp := c.Coordinate(&cmd)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if cmd.Command != coordinator.SessionCmdPoll {
|
|
log.Printf("sending: %v", resp)
|
|
}
|
|
err = conn.WriteJSON(resp)
|
|
if err != nil {
|
|
log.Println("Error during message writing:", err)
|
|
break
|
|
}
|
|
if resp.Result == coordinator.SessionRespLeft {
|
|
time.Sleep(1 * time.Second) //give clients a second to respond
|
|
break
|
|
}
|
|
}
|
|
}
|