Added name duplicate handler by modifying the ClientHandler class as well as adding a class where all Client names are stored

This commit is contained in:
Alexander Sazonov 2022-03-27 00:38:48 +01:00
parent 4b3d3127ad
commit 10bbcdf69e
4 changed files with 26 additions and 2 deletions

View File

@ -1,6 +1,7 @@
package ch.unibas.dmi.dbis.cs108.multiplayer.client;
import ch.unibas.dmi.dbis.cs108.multiplayer.protocol.NoLegalProtocolCommandStringFoundException;
import ch.unibas.dmi.dbis.cs108.multiplayer.server.NameGenerator;
import java.net.Socket;
import java.io.*;
@ -20,7 +21,6 @@ public class Client {
this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
this.in = new BufferedReader((new InputStreamReader((socket.getInputStream()))));
String randomUserName = NameGenerator.randomName();
//TODO hide connecting logik(next 4 lines)
this.userName = userName;
this.out.write(getUsername());
@ -147,4 +147,6 @@ public class Client {
public String getUsername() {
return userName;
}
}

View File

@ -0,0 +1,14 @@
package ch.unibas.dmi.dbis.cs108.multiplayer.server;
/* This class is built to contain the usernames of all players in a single string.
* This allows a duplicate check (--> ClientHandler) when a new player chooses
* a name: does the string with all the previous names contain the new player's
* desired username? If yes, he is being assigned a random name. If no, he can keep
* his desired name. */
public class AllClientNames {
static StringBuilder names = new StringBuilder();
public static String allNames(String currentName) {
return names.append(currentName).toString();
}
}

View File

@ -28,6 +28,14 @@ public class ClientHandler implements Runnable {
this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
this.in = new BufferedReader((new InputStreamReader((socket.getInputStream()))));
this.clientUserName = in.readLine();
// duplicate handling: if username already taken, assign random name to client
if (AllClientNames.allNames("").contains(clientUserName)) {
clientUserName = NameGenerator.randomName();
}
// add username to list of all client names for future duplicate checking
AllClientNames.allNames(clientUserName);
connectedClients.add(this);
broadcastMessage("SERVER: " + clientUserName + " has joined the Server");
} catch (IOException e) {

View File

@ -1,4 +1,4 @@
package ch.unibas.dmi.dbis.cs108.multiplayer.client;
package ch.unibas.dmi.dbis.cs108.multiplayer.server;
import java.util.Random;