Chapter 22 Networking: Streams-Based Sockets and Datagrams 1131 (Starting a web site)
Chapter 22 Networking: Streams-Based Sockets and Datagrams 1131 248 // signal the move is invalid 249 else 250 writer.Write( “Invalid move, try again” ); 251 252 // if game is over, set done to true to exit while loop 253 if ( server.GameOver() ) 254 done = true; 255 256 } // end while loop 257 258 // close the socket connection 259 writer.Close(); 260 reader.Close(); 261 socketStream.Close(); 262 connection.Close(); 263 264 } // end method Run 265 266 } // end class Player Fig. 22.5 Fig. 22.FiFig. 22.5g. 22.5Server side of client/server Tic-Tac-Toe program. (Part 6 of 6.) Fig. 22.5 Server(Fig. 22.5) uses its constructor (lines 35 48) to create a bytearray to store the moves the players have made (line 39). The program creates an array of two references to Player objects (line 41) and an array of two references to Thread objects (line 42). Each element in both arrays corresponds to a Tic-Tac-Toe player. Variable current- Playeris set to 0, which corresponds to player “X.”In our program, player “X”makes the first move (line 43). Lines 46 47 create and start ThreadgetPlayers, which the Server uses to accept connections so that the current Thread does not block while awaiting players. Thread getPlayers executes method SetUp (lines 65 92), which creates a TcpListenerobject to listen for requests on port 5000(lines 68 69). This object then listens for connection requests from the first and second players. Lines 72 73 and 79 80 instantiate Playerobjects representing the players, and lines 74 75 and 81 82 create two Threads that execute the Runmethods of each Playerobject. The Player constructor (Fig. 22.5, lines 165 181) receives as arguments a reference to the Socket object (i.e., the connection to the client), a reference to the Server object and an intindicating the mark (”X”or “O”) used by that player. In this case study, Server calls method Run(lines 193 264) after instantiating a Playerobject. Lines 198 206 notify the server of a successful connection and send to the client the charthat the client will place on the board when making a move. If Runis executing for Player”X”, lines 211 221 execute, causing Player”X” to wait for a second player to connect. Lines 217 218 define a whileloop that suspends the Player”X”Threaduntil the server signals that Player “O” has connected. The server notifies the Player of the connection by setting the Player s threadSuspendedvariable to false(line 89). When threadSuspended becomes false, Playerexits the whileloop of lines 217 218. Method Runexecutes the while structure (lines 226 256), enabling the user to play the game. Each iteration of this structure waits for the client to send an int specifying where on the board to place the “X” or “O” the Player then places the mark on the
Note: If you are looking for reliable webhost to maintain and run your java application check Vision java hosting services