Java Reference
In-Depth Information
31.9
How does a server receive connection from a client? How does a client connect to a
server?
Check
Point
31.10
How do you find the host name of a client program from the server?
31.11
How do you send and receive an object?
31.6 Case Study: Distributed Tic-Tac-Toe Games
This section develops a program that enables two players to play the tic-tac-toe game
on the Internet.
Key
Point
In Section  16.12, Case Study: Developing a Tic-Tac-Toe Game, you developed a program
for a tic-tac-toe game that enables two players to play the game on the same machine. In this
section, you will learn how to develop a distributed tic-tac-toe game using multithreads and
networking with socket streams. A distributed tic-tac-toe game enables users to play on dif-
ferent machines from anywhere on the Internet.
You need to develop a server for multiple clients. The server creates a server socket and
accepts connections from every two players to form a session. Each session is a thread that
communicates with the two players and determines the status of the game. The server can
establish any number of sessions, as shown in Figure 31.13.
For each session, the first client connecting to the server is identified as player 1 with token
X , and the second client connecting is identified as player 2 with token O . The server notifies
the players of their respective tokens. Once two clients are connected to it, the server starts a
thread to facilitate the game between the two players by performing the steps repeatedly, as
shown in Figure 31.13.
Server
...
Session 1
Session n
Player 1
Player 2
...
Player 1
Player 2
F IGURE 31.12
The server can create many sessions, each of which facilitates a tic-tac-toe
game for two players.
The server does not have to be a graphical component, but creating it in a GUI in which
game information can be viewed is user-friendly. You can create a scroll pane to hold a text
area in the GUI and display game information in the text area. The server creates a thread to
handle a game session when two players are connected to the server.
The client is responsible for interacting with the players. It creates a user interface with
nine cells and displays the game title and status to the players in the labels. The client class is
very similar to the TicTacToe class presented in the case study in Listing 16.13. However,
the client in this example does not determine the game status (win or draw); it simply passes
the moves to the server and receives the game status from the server.
Based on the foregoing analysis, you can create the following classes:
TicTacToeServer serves all the clients in Listing 31.9.
HandleASession facilitates the game for two players. This class is defined in
TicTacToeServer.java.
 
 
 
Search WWH ::




Custom Search