Fix waiting for websockets connection.

This commit is contained in:
Marco 2023-06-06 22:58:33 +02:00
parent e90fb7a0dc
commit b6bb75376d
4 changed files with 64 additions and 26 deletions

View File

@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"local/m/mchess_server/api" "local/m/mchess_server/api"
"log" "log"
"time"
"github.com/google/uuid" "github.com/google/uuid"
) )
@ -27,25 +28,28 @@ func NewGame() *Game {
return &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] return game.players[0]
} }
func (game Game) getPlayer2() *Player { func (game Game) GetPlayer2() *Player {
return game.players[1] return game.players[1]
} }
func (game *Game) Handle() { func (game *Game) Handle() {
defer log.Println("Game ", game.id, ": handle() ended") defer game.killGame()
log.Println("Game ", game.id, " started") ok := game.waitForWebsocketConnections()
<-game.getPlayer1().wsConnEstablished if !ok {
log.Println("WS connection for player 1 established") return
<-game.getPlayer2().wsConnEstablished }
log.Println("WS connection for player 2 established")
gameState := PlayerToMove gameState := PlayerToMove
game.currentTurnPlayer = game.getPlayer1() game.currentTurnPlayer = game.GetPlayer1()
var move api.Move var move api.Move
var receivedMessage []byte var receivedMessage []byte
var err error var err error
@ -54,7 +58,6 @@ func (game *Game) Handle() {
switch gameState { switch gameState {
case PlayerToMove: case PlayerToMove:
_, receivedMessage, err = game.currentTurnPlayer.ReadMessageFromPlayer() _, receivedMessage, err = game.currentTurnPlayer.ReadMessageFromPlayer()
if err != nil { if err != nil {
log.Println("Error while reading message:", err) log.Println("Error while reading message:", err)
@ -72,19 +75,18 @@ func (game *Game) Handle() {
gameState = CheckPlayerChange gameState = CheckPlayerChange
case CheckPlayerChange: case CheckPlayerChange:
if game.currentTurnPlayer.Uuid == game.players[0].Uuid { if game.currentTurnPlayer.Uuid == game.players[0].Uuid {
game.currentTurnPlayer = game.players[1] game.currentTurnPlayer = game.players[1]
} else { } else {
game.currentTurnPlayer = game.players[0] game.currentTurnPlayer = game.players[0]
} }
err := game.getPlayer1().WriteMessageToPlayer(receivedMessage) err := game.GetPlayer1().WriteMessageToPlayer(receivedMessage)
if err != nil { if err != nil {
log.Println("Error during message writing:", err) log.Println("Error during message writing:", err)
continue continue
} }
err = game.getPlayer2().WriteMessageToPlayer(receivedMessage) err = game.GetPlayer2().WriteMessageToPlayer(receivedMessage)
if err != nil { if err != nil {
log.Println("Error during message writing:", err) log.Println("Error during message writing:", err)
continue continue
@ -103,3 +105,26 @@ func (game *Game) Handle() {
func (game *Game) AddPlayersToGame(player *Player) { func (game *Game) AddPlayersToGame(player *Player) {
game.players = append(game.players, 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
}

View File

@ -3,6 +3,7 @@ package chess
import ( import (
"context" "context"
"log" "log"
"time"
"github.com/google/uuid" "github.com/google/uuid"
"nhooyr.io/websocket" "nhooyr.io/websocket"
@ -25,8 +26,8 @@ func NewPlayer(uuid uuid.UUID) *Player {
} }
} }
func (p *Player) SetConnection(ctx context.Context, conn websocket.Conn) { func (p *Player) SetConnection(ctx context.Context, conn *websocket.Conn) {
p.Conn = &conn p.Conn = conn
p.context = ctx p.context = ctx
p.wsConnEstablished <- true p.wsConnEstablished <- true
} }
@ -43,3 +44,14 @@ func (p *Player) ReadMessageFromPlayer() (websocket.MessageType, []byte, error)
return msgType, msg, err 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
}
}

View File

@ -7,10 +7,9 @@ import (
) )
type Lobby struct { type Lobby struct {
Uuid uuid.UUID Uuid uuid.UUID
players []*chess.Player
Game chess.Game Game *chess.Game
PlayerJoined chan bool PlayerJoined chan bool
} }
@ -18,13 +17,12 @@ type Lobby struct {
func NewEmptyLobbyWithUUID(uuid uuid.UUID) *Lobby { func NewEmptyLobbyWithUUID(uuid uuid.UUID) *Lobby {
return &Lobby{ return &Lobby{
Uuid: uuid, Uuid: uuid,
Game: *chess.NewGame(), Game: chess.NewGame(),
PlayerJoined: make(chan bool), PlayerJoined: make(chan bool),
} }
} }
func (w *Lobby) AddPlayerAndStartGameIfFull(player *chess.Player) { func (w *Lobby) AddPlayerAndStartGameIfFull(player *chess.Player) {
w.players = append(w.players, player)
w.Game.AddPlayersToGame(player) w.Game.AddPlayersToGame(player)
if w.IsFull() { if w.IsFull() {
go w.Game.Handle() go w.Game.Handle()
@ -32,11 +30,11 @@ func (w *Lobby) AddPlayerAndStartGameIfFull(player *chess.Player) {
} }
func (w *Lobby) IsFull() bool { 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) { 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 { if player.Uuid == uuid {
return player, true return player, true
} }
@ -45,9 +43,9 @@ func (l *Lobby) GetPlayerByUUID(uuid uuid.UUID) (*chess.Player, bool) {
} }
func (l *Lobby) GetPlayer1() *chess.Player { func (l *Lobby) GetPlayer1() *chess.Player {
return l.players[0] return l.Game.GetPlayer1()
} }
func (l *Lobby) GetPlayer2() *chess.Player { func (l *Lobby) GetPlayer2() *chess.Player {
return l.players[1] return l.Game.GetPlayer2()
} }

View File

@ -38,6 +38,9 @@ func main() {
log.Println("Starting service WITHOUT TLS") log.Println("Starting service WITHOUT TLS")
log.Fatal(router.Run("localhost:8080")) log.Fatal(router.Run("localhost:8080"))
} else { } 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")) log.Fatal(autotls.Run(router, "chess.sw-gross.de"))
} }
} }
@ -69,10 +72,10 @@ func registerWebSocketConnection(c *gin.Context) {
log.Println(err) log.Println(err)
return 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) msgType, msg, err := conn.Read(ctx)
if err != nil { if err != nil {
errorMessage := fmt.Sprintf("Reading from websocket connection did not work: %s", err) errorMessage := fmt.Sprintf("Reading from websocket connection did not work: %s", err)