/** * A server for a network multi-player tic tac toe game. Modified and * extended from the class presented in Deitel and Deitel "Java How to * Program" book. I made a bunch of enhancements and rewrote large sections * of the code. The main change is instead of passing *data* between the * client and server, I made a TTTP (tic tac toe protocol) which is totally * plain text, so you can test the game with Telnet (always a good idea.) * The strings that are sent in TTTP are: * * Client -> Server Server -> Client * ---------------- ---------------- * MOVE <n> (0 <= n <= 8) WELCOME <char> (char in {X, O}) * QUIT VALID_MOVE * OTHER_PLAYER_MOVED <n> * VICTORY * DEFEAT * TIE * MESSAGE <text> * * A second change is that it allows an unlimited number of pairs of * players to play. */public class TicTacToeServer {

/** * A board has nine squares. Each square is either unowned or * it is owned by a player. So we use a simple array of player * references. If null, the corresponding square is unowned, * otherwise the array cell stores a reference to the player that * owns it. */ private Player[] board = { null, null, null, null, null, null, null, null, null};

/** * Called by the player threads when a player tries to make a * move. This method checks to see if the move is legal: that * is, the player requesting the move must be the current player * and the square in which she is trying to move must not already * be occupied. If the move is legal the game state is updated * (the square is set and the next player becomes current) and * the other player is notified of the move so it can update its * client. */ public synchronized boolean legalMove(int location, Player player) { if (player == currentPlayer && board[location] == null) { board[location] = currentPlayer; currentPlayer = currentPlayer.opponent; currentPlayer.otherPlayerMoved(location); return true; } return false; }

/** * The class for the helper threads in this multithreaded server * application. A Player is identified by a character mark * which is either 'X' or 'O'. For communication with the * client the player has a socket with its input and output * streams. Since only text is being communicated we use a * reader and a writer. */ class Player extends Thread { char mark; Player opponent; Socket socket; BufferedReader input; PrintWriter output;