2021-10-01 14:29:05 -04:00
|
|
|
package main
|
2021-10-01 14:24:31 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"git.saintnet.tech/tomecraft/tome_lib"
|
|
|
|
coordinator "git.saintnet.tech/tomecraft/tome_server"
|
|
|
|
"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 tome_lib.SessionCommand
|
|
|
|
err := conn.ReadJSON(&cmd)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Error during message reading:", err)
|
|
|
|
break
|
|
|
|
}
|
2021-10-02 13:26:49 -04:00
|
|
|
if cmd.Command != tome_lib.SessionCmdPoll && (cmd.GameCommand != nil && cmd.GameCommand.Type != tome_lib.StateCmd && cmd.GameCommand.Cmd != "g") {
|
2021-10-01 14:24:31 -04:00
|
|
|
log.Printf("Received: %s", cmd)
|
|
|
|
}
|
|
|
|
resp := c.Coordinate(&cmd)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2021-10-02 13:26:49 -04:00
|
|
|
if cmd.Command != tome_lib.SessionCmdPoll && (cmd.GameCommand != nil && cmd.GameCommand.Type != tome_lib.StateCmd && cmd.GameCommand.Cmd != "g") {
|
2021-10-01 14:24:31 -04:00
|
|
|
log.Printf("sending: %v", resp.Result)
|
|
|
|
}
|
|
|
|
err = conn.WriteJSON(resp)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Error during message writing:", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if resp.Result == tome_lib.SessionRespLeft {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|