I have a TCP server, and I need to keep the connection open until a another player connects. I'm creating a ticker so that I can send a message to the player so that he knows the server is waiting on another player to connect.
The problem is that the player that connects get instant disconnect because of the defer func(). How can I make it that the player waiting isn't getting instant disconnect?
func handleConnection(c net.Conn, msgchan chan<- string, addchan chan<- Client, rmchan chan<- Client) {
bufc := bufio.NewReader(c)
defer c.Close()
client := Client{
conn: c,
nickname: promptNick(c, bufc),
ch: make(chan string),
game: nil,
}
// Register user
addchan <- client
defer func() {
msgchan <- fmt.Sprintf("User %s left the game room.
", client.nickname)
log.Printf("Connection from %v closed.
", c.RemoteAddr())
rmchan <- client
}()
io.WriteString(c, fmt.Sprintf("Welcome, %s!
", client.nickname))
msgchan <- fmt.Sprintf("New user %s has joined the game room.
", client.nickname)
// Here the magic I'm trying to make work
quit := make(chan struct{})
if len(clients) != 0 && len(clients)%2 == 0 {
close(quit)
var black *Client
var white *Client
for _, player := range clients {
if player.game == nil && black == nil {
black = player
} else if player.game == nil && white == nil {
white = player
}
if black != nil && white != nil {
black.ch <- "New game started, you are matched with " + white.nickname
white.ch <- "New game started, you are matched with " + black.nickname
newGame(black, white)
break
}
}
go client.ReadMove(msgchan)
client.WriteLinesFrom(client.ch)
} else {
ticker := time.NewTicker(5 * time.Second)
go func() {
for {
select {
case <-ticker.C:
client.ch <- "Waiting for another player to connect...
"
case <-quit:
ticker.Stop()
return
}
}
}()
}
}