snengame/cmd/server/server.go

63 lines
1.4 KiB
Go
Raw Normal View History

2021-07-25 16:32:41 -04:00
package main
2021-07-22 15:37:25 -04:00
import (
"log"
"net/http"
"time"
2021-07-22 15:37:25 -04:00
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
})
2021-09-23 13:04:34 -04:00
log.Println("starting websocket")
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
}
2021-07-26 13:02:00 -04:00
if cmd.Command != coordinator.SessionCmdPoll {
log.Printf("Received: %s", cmd)
}
2021-07-22 18:19:21 -04:00
resp := c.Coordinate(&cmd)
if err != nil {
panic(err)
}
2021-07-26 13:02:00 -04:00
if cmd.Command != coordinator.SessionCmdPoll {
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 {
time.Sleep(1 * time.Second) //give clients a second to respond
2021-07-22 18:19:21 -04:00
break
}
2021-07-22 15:37:25 -04:00
}
}