I have a multi-threaded network/client program that plays a game of tic-tac-toe.
I always begin by asking the client if he's a new or existing player.
If he's a new player, I ask him what he wants his username and symbol to be, and then I create a new player. I also check to make sure the username isn't already taken.
Now, since both players are playing concurrently in their own thread, it is feasible that two player connect with each other, each of which are new players, and then both choose to create the same username.
Since one player may still be "being created", his username won't be in the file yet. Which means that even though the second player chooses the same username, the game will think it's unused / valid because the server hasn't written the first player's username to the file yet.
Here's a shortened version of the code:
public void run() { try { outputToClient.writeInt(1); // signal the client both players are connected and it's time to establish the players processMessage(input.readLine()); // client tells server whether user is new or existing // server responds by accordingly creating or retrieving new player outputToClient.writeInt(playerNumber); } catch (IOException ex) { System.err.println(ex); } } public synchronized void processMessage(String message) { if (message.equals("new")) { try { boolean new_name = true; do { name = input.readLine(); new_name = checkNewName(name); if (new_name) { System.out.println("The new name is : " + name); outputToClient.writeBytes("Name not taken\n"); } else { System.out.println("The taken name is : " + name); outputToClient.writeBytes("Name taken\n"); } } while(!new_name); symbol = input.readLine().charAt(0); } catch (IOException ex) { System.err.println(ex); } createPlayer(); } else { String clientName = ""; try { clientName = input.readLine(); } catch (IOException ex) { System.err.println(ex); } retrievePlayer(clientName); } Symbols[playerNumber] = symbol; }
The idea here is that by making "processMessage" synchronized, only one thread will be giving a name / creating a player at a time, so we know there will be no overlap. Yet it's not working....
What am I doing wrong?