Skip to content

Commit

Permalink
feat: LobbyPacket using deep copy on ArrayList
Browse files Browse the repository at this point in the history
  • Loading branch information
LapisBerry committed May 23, 2024
1 parent a913bff commit f97d740
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 8 deletions.
9 changes: 2 additions & 7 deletions src/main/java/com/lapisberry/net/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import com.lapisberry.net.packets.LobbyPacket;
import com.lapisberry.net.packets.ServerPacket;
import com.lapisberry.utils.Config;
import javafx.util.Pair;

import java.io.IOException;
import java.net.ServerSocket;
Expand Down Expand Up @@ -66,9 +65,7 @@ public void processPacketFromClient(ClientHandler sender, ClientPacket packet) {
System.out.println("Processing packet from " + sender.getSocket().getInetAddress().getHostAddress() + ": " + packet);
if (packet instanceof JoinRequestPacket joinRequestPacket) {
serverLobby.addPlayer(sender.getClientId(), joinRequestPacket.getUsername());
// Have to make a copy of the players list to avoid shared reference
ArrayList<Pair<Integer, String>> players = new ArrayList<>(serverLobby.getPlayers());
sendPacketToAllClients(new LobbyPacket(players));
sendPacketToAllClients(new LobbyPacket(serverLobby.getPlayers()));
}
}

Expand All @@ -83,8 +80,6 @@ public void close() {
public void removeClientHandler(ClientHandler clientHandler) {
clientHandlers.remove(clientHandler);
serverLobby.removePlayer(clientHandler.getClientId());
// Have to make a copy of the players list to avoid shared reference
ArrayList<Pair<Integer, String>> players = new ArrayList<>(serverLobby.getPlayers());
sendPacketToAllClients(new LobbyPacket(players));
sendPacketToAllClients(new LobbyPacket(serverLobby.getPlayers()));
}
}
3 changes: 2 additions & 1 deletion src/main/java/com/lapisberry/net/packets/LobbyPacket.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public class LobbyPacket extends ServerPacket implements Serializable {

// Constructors
public LobbyPacket(ArrayList<Pair<Integer, String>> players) {
this.players = players;
// deep copy
this.players = new ArrayList<>(players);
}

// Methods
Expand Down

0 comments on commit f97d740

Please sign in to comment.