fix(server): disconnects clients who crash/exit
This commit is contained in:
parent
e0380e44c3
commit
350b000e23
@ -5,9 +5,11 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const PORT = ":5518"
|
||||
@ -159,7 +161,8 @@ func handleClient(conn net.Conn) {
|
||||
var packetId PacketID
|
||||
packetId, data, err := readPacket(conn)
|
||||
if err != nil {
|
||||
fmt.Println("Error reading packet:", err)
|
||||
fmt.Println("Error reading packet (handleclient) :", err)
|
||||
handleLeaveRoom(conn)
|
||||
return
|
||||
}
|
||||
|
||||
@ -354,13 +357,12 @@ func handleLeaveRoom(conn net.Conn) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if leavingClient == nil {
|
||||
fmt.Println("Client not found")
|
||||
return
|
||||
}
|
||||
|
||||
room := findRoom(leavingClient.RoomCode)
|
||||
room := rooms[leavingClient.RoomCode]
|
||||
if room == nil {
|
||||
fmt.Println("Room not found")
|
||||
return
|
||||
@ -368,30 +370,31 @@ func handleLeaveRoom(conn net.Conn) {
|
||||
|
||||
for i, client := range room.Clients {
|
||||
if client == leavingClient {
|
||||
// Remove the client from the list
|
||||
room.Clients = append(room.Clients[:i], room.Clients[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// If the room is now empty or the leaving client was the creator, delete the room
|
||||
if len(room.Clients) == 0 || room.Clients[0] == leavingClient {
|
||||
for _, client := range room.Clients {
|
||||
client.Conn.Close()
|
||||
}
|
||||
|
||||
// Delete the room if its empty
|
||||
if len(room.Clients) == 0 {
|
||||
delete(rooms, room.Code)
|
||||
fmt.Println("Room", room.Code, "deleted")
|
||||
} else {
|
||||
// // Notify remaining clients that a user has left (optional)
|
||||
// for _, remainingClient := range room.Clients {
|
||||
// writePacket(remainingClient.Conn, byte(LEAVE_ROOM), []byte(fmt.Sprintf("User %s has left the room", leavingClient.ClientID)))
|
||||
// }
|
||||
}
|
||||
|
||||
delete(clients, leavingClient.ClientID)
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
leavingClient.Conn.Close()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
log.Fatalln("Timeout while closing leaving client's connection")
|
||||
}
|
||||
|
||||
fmt.Println("Client", leavingClient.ClientID, "left the room and connection closed")
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user