Client/server demo code

This is an example of a network protocol for a very simple client-server application. The application is unfinished! For example, the Model interface includes addChangeListener and removeChangeListener methods, which are implemented by the Model class, but no other class makes use of those methods. Also, there are very few comments, Javadoc or otherwise, anywhere in the source code. I will extend the example if time permits.

Here is a class diagram of the application:

And here are the source files:

BogusCommand1.java
BogusCommand2.java
CommandObject.java
ControlObject.java
GameClient1.java
GameServer.java
GameWorld.java
GenericResponse.java
MiniServer.java
Model.java
ModelChangeEvent.java
ModelChangeListener.java
MsgBuilder.java
MsgSender.java
Nameable.java
NameChanger.java
Packetizer.java
Player.java
ResponseObject.java
Stoppable.java
Stopper.java
XSBuilder.java

The GameServer class

When GameServer starts up, it creates a World object. As each client connects, GameServer spawns a new MiniServer thread to handle the connection, passing it a reference to the World.

Each MiniServer creates one Player and registers it with the World, and represents that Player to the client. (A better architecture would allow the client to describe its needs; some clients might not want to represent a character.)

The Player class

Each player has a name and an (x,y) location. Other methods can be added as required. (The locations are stored as fields, xpos and ypos. The design should use accessor/mutator methods instead.)

Object i/o and the Packetizer class

The Packetizer class provides asynchronous i/o for both clients and server. A Packetizer creates its own low-level thread which monitors a socket for incoming data, assembling incoming characters into messages and formatting outgoing messages into character streams. As messages are received, they are placed in a queue, from which they can be retrieved with the readMessage(...) method. A messageAvailable(...) method allows client code to determine whether a message is available.

Packetizer performs explicit byte-to-character translation on the incoming and outgoing streams. Its current version is hard-coded to use ISO-8859-1, but it would be trivial to support an alternate encoding.

Packetizer does not impose any particular messaging protocol on the underlying connection. Instead, it delegates message building and message parsing to another object, which must implement the MsgBuilder interface. This demo includes one such class, XSBuilder, which uses the XStream library to convert objects to XML.