From b6bb75376de24d7b0be73bc1250dff3f2dafb847 Mon Sep 17 00:00:00 2001 From: Marco Date: Tue, 6 Jun 2023 22:58:33 +0200 Subject: [PATCH] Fix waiting for websockets connection. --- chess/game.go | 51 ++++++++++++++++++++++++++++++----------- chess/player.go | 16 +++++++++++-- lobby_registry/lobby.go | 16 ++++++------- main.go | 7 ++++-- 4 files changed, 64 insertions(+), 26 deletions(-) diff --git a/chess/game.go b/chess/game.go index e95e49a..f97ed56 100644 --- a/chess/game.go +++ b/chess/game.go @@ -4,6 +4,7 @@ import ( "encoding/json" "local/m/mchess_server/api" "log" + "time" "github.com/google/uuid" ) @@ -27,25 +28,28 @@ func NewGame() *Game { return &game } -func (game Game) getPlayer1() *Player { +func (game Game) GetPlayers() []*Player { + return game.players +} + +func (game Game) GetPlayer1() *Player { return game.players[0] } -func (game Game) getPlayer2() *Player { +func (game Game) GetPlayer2() *Player { return game.players[1] } func (game *Game) Handle() { - defer log.Println("Game ", game.id, ": handle() ended") + defer game.killGame() - log.Println("Game ", game.id, " started") - <-game.getPlayer1().wsConnEstablished - log.Println("WS connection for player 1 established") - <-game.getPlayer2().wsConnEstablished - log.Println("WS connection for player 2 established") + ok := game.waitForWebsocketConnections() + if !ok { + return + } gameState := PlayerToMove - game.currentTurnPlayer = game.getPlayer1() + game.currentTurnPlayer = game.GetPlayer1() var move api.Move var receivedMessage []byte var err error @@ -54,7 +58,6 @@ func (game *Game) Handle() { switch gameState { case PlayerToMove: - _, receivedMessage, err = game.currentTurnPlayer.ReadMessageFromPlayer() if err != nil { log.Println("Error while reading message:", err) @@ -72,19 +75,18 @@ func (game *Game) Handle() { gameState = CheckPlayerChange case CheckPlayerChange: - if game.currentTurnPlayer.Uuid == game.players[0].Uuid { game.currentTurnPlayer = game.players[1] } else { game.currentTurnPlayer = game.players[0] } - err := game.getPlayer1().WriteMessageToPlayer(receivedMessage) + err := game.GetPlayer1().WriteMessageToPlayer(receivedMessage) if err != nil { log.Println("Error during message writing:", err) continue } - err = game.getPlayer2().WriteMessageToPlayer(receivedMessage) + err = game.GetPlayer2().WriteMessageToPlayer(receivedMessage) if err != nil { log.Println("Error during message writing:", err) continue @@ -103,3 +105,26 @@ func (game *Game) Handle() { func (game *Game) AddPlayersToGame(player *Player) { game.players = append(game.players, player) } + +func (game *Game) killGame() { + log.Println("Game should be killed") +} + +func (game *Game) waitForWebsocketConnections() bool { + timer := time.NewTimer(5 * time.Second) + numberOfConnections := 0 + waitingForPlayers := make(chan bool) + + go game.GetPlayer1().WaitForWebsocketConnection(waitingForPlayers) + go game.GetPlayer2().WaitForWebsocketConnection(waitingForPlayers) + + for numberOfConnections < 2 { + select { + case <-waitingForPlayers: + numberOfConnections++ + case <-timer.C: + return false + } + } + return true +} diff --git a/chess/player.go b/chess/player.go index d54afc0..a978f4e 100644 --- a/chess/player.go +++ b/chess/player.go @@ -3,6 +3,7 @@ package chess import ( "context" "log" + "time" "github.com/google/uuid" "nhooyr.io/websocket" @@ -25,8 +26,8 @@ func NewPlayer(uuid uuid.UUID) *Player { } } -func (p *Player) SetConnection(ctx context.Context, conn websocket.Conn) { - p.Conn = &conn +func (p *Player) SetConnection(ctx context.Context, conn *websocket.Conn) { + p.Conn = conn p.context = ctx p.wsConnEstablished <- true } @@ -43,3 +44,14 @@ func (p *Player) ReadMessageFromPlayer() (websocket.MessageType, []byte, error) return msgType, msg, err } + +func (p *Player) WaitForWebsocketConnection(c chan bool) { + timer := time.NewTimer(500 * time.Second) + + select { + case <-p.wsConnEstablished: + c <- true + case <-timer.C: + return + } +} diff --git a/lobby_registry/lobby.go b/lobby_registry/lobby.go index db427dc..810b34b 100644 --- a/lobby_registry/lobby.go +++ b/lobby_registry/lobby.go @@ -7,10 +7,9 @@ import ( ) type Lobby struct { - Uuid uuid.UUID - players []*chess.Player + Uuid uuid.UUID - Game chess.Game + Game *chess.Game PlayerJoined chan bool } @@ -18,13 +17,12 @@ type Lobby struct { func NewEmptyLobbyWithUUID(uuid uuid.UUID) *Lobby { return &Lobby{ Uuid: uuid, - Game: *chess.NewGame(), + Game: chess.NewGame(), PlayerJoined: make(chan bool), } } func (w *Lobby) AddPlayerAndStartGameIfFull(player *chess.Player) { - w.players = append(w.players, player) w.Game.AddPlayersToGame(player) if w.IsFull() { go w.Game.Handle() @@ -32,11 +30,11 @@ func (w *Lobby) AddPlayerAndStartGameIfFull(player *chess.Player) { } func (w *Lobby) IsFull() bool { - return len(w.players) == 2 + return len(w.Game.GetPlayers()) == 2 } func (l *Lobby) GetPlayerByUUID(uuid uuid.UUID) (*chess.Player, bool) { - for _, player := range l.players { + for _, player := range l.Game.GetPlayers() { if player.Uuid == uuid { return player, true } @@ -45,9 +43,9 @@ func (l *Lobby) GetPlayerByUUID(uuid uuid.UUID) (*chess.Player, bool) { } func (l *Lobby) GetPlayer1() *chess.Player { - return l.players[0] + return l.Game.GetPlayer1() } func (l *Lobby) GetPlayer2() *chess.Player { - return l.players[1] + return l.Game.GetPlayer2() } diff --git a/main.go b/main.go index 9e13e72..6f77f40 100644 --- a/main.go +++ b/main.go @@ -38,6 +38,9 @@ func main() { log.Println("Starting service WITHOUT TLS") log.Fatal(router.Run("localhost:8080")) } else { + gin.SetMode(gin.ReleaseMode) + log.Println("Starting in release mode") + log.Println("Starting service with TLS") log.Fatal(autotls.Run(router, "chess.sw-gross.de")) } } @@ -69,10 +72,10 @@ func registerWebSocketConnection(c *gin.Context) { log.Println(err) return } - go waitForAndHandlePlayerID(c, *webSocketConn) + go waitForAndHandlePlayerID(c, webSocketConn) } -func waitForAndHandlePlayerID(ctx context.Context, conn websocket.Conn) { +func waitForAndHandlePlayerID(ctx context.Context, conn *websocket.Conn) { msgType, msg, err := conn.Read(ctx) if err != nil { errorMessage := fmt.Sprintf("Reading from websocket connection did not work: %s", err)