TicTacToe: Java RMI with serialized objects and callbacks
This site illustrates using Java RMI with a serialized object and
with callbacks. Note: this code requires the server job to be on a
separate computer from the client.
The files:
- TTTBoard.java: a TicTacToe board
object; this keeps track of the state of the tic tac toe game.
- TTTService.java: the interface
for the tic tac toe board server.
- TTTServiceImpl.java: the
implementation of the above interface.
- TicTacToe.java: A frame which
illustrates accessing and updating the tic tac toe board that's stored on
the server. If there are multiple clients, each will be updated whenever
there's a change to the board. The program does not check which
client clicks for X's or O's; it assumes all users are cooperating and know
when they should play.
- TTTClientRemote.java: this
class allows the server to "call back" to the client each time the board
changes state.
The pieces that are needed for supporting callbacks (that is, the server
sending data to the client whenever there is a change) are
Thus when any one client sends an update operation to the server, all
clients see the new board state.
To compile and run the example, do the following:
- Download the files to the machine that will be your host.
- On the host machine, edit ServiceName and ServicePort
in TTTServiceImpl.java to use
unique values.
- Still on the host machine, compile the service by typing
javac TTTServiceImpl.java
- Recompile the code on the host:
javac TTTServiceImpl.java
- Copy the files to your client side - making sure the copy has the same
entry for ServiceName and ServicePort - and compile them:
javac TicTacToe.java
- Switch back to the host and type
rmiregistry xxxx
where xxxx is the port number you used for
ServicePort. For example, I type "rmiregistry 10000".
- Start up another command-line prompt window on the host and type
java TTTServiceImpl
- Back on the client, run the game:
java TicTacToe
You should now be able to select squares and generate a winner. You could
try running TicTacToe on another PC as well (as another client),
but you'll quickly see that things don't work well.