Java Reference
In-Depth Information
DVDSocketClient
makes use of the
DVDCommand
object in each of its
DBClient
methods. For
example, in the
find
method, the command object is constructed with the FIND
enum
value of
SocketCommand
. Next, the
regex
attribute is set using the query parameter of the
find
method.
These two steps are shown again here:
DvdCommand cmdObj = new DvdCommand(SocketCommand.FIND);
cmdObj.setRegex(query);
The Result Object
The
DVDResult
object is used to encapsulate the result of the request. When the
DVDDatabase
has completed a request, the result is sent back to
DVDSocketServer
, which in turn wraps
the result in a
DVDResult
object and sends it back to the socket client. As in the case of the
command object,
DVDResult
must be serializable since it is sent across the network. Even
exceptions are wrapped in
DVDResult
and sent back to the client.
The result object is similar to the
DVDCommand
object in its operation. There are a number
of constructors that take the varying types of return values from the
DBClient
methods. You
can find the code in the project download, but the following is an example of its usage in the
find
method of
DVDSocketClient
:
DVDResult serialReturn = (DVDResult)ois.readObject();
if (!serialReturn.isException()) {
retVal = serialReturn.getCollection();
}
The
DVDResult
is received from the socket server. The result object is checked for excep-
tions, and if no exceptions are detected, the
Collection
is extracted from
DVDResult
. We
know it must be a
Collection
since our protocol ensures that for
DBClient
's
find
method,
a
Collection
is always returned.
■
Note
Our application protocol was separated from our socket server, based on good design principles.
Thus, changes in our protocol, or even additional protocols, can now be handled without affecting the socket
server directly.
USING ENUM CONSTANTS
The Application protocol is implemented by specifying the command type. This was performed with the fol-
lowing code taken from the constructor of the
DvdCommand
class:
public DvdCommand(SocketCommand command, DVD dvd) {
setCommandId(command);
this.dvd = dvd;
}