Java Reference
In-Depth Information
while (true) {
Socket aSocket = aServerSocket.accept();
DbSocketRequest request = new DbSocketRequest(dbLocation, aSocket);
request.start();
}
}
}
The main method creates a ServerSocket object on port 3000. There is a loop that listens
for requests from any Java or non-Java clients on port 3000. Once a request is received, the
connection is accepted, meaning that the accept method stops blocking and the Socket object
is returned. The resulting socket is passed in as a parameter to the DBSocketRequest . The
server socket then spawns a new thread for the client request. This design enables multiple
clients to connect to the socket server since each request is serviced in a separate thread.
The DBSocketRequest class extends Thread . You will recall that one of the requirements is
that multiple clients need to be able to use the DVDDatabase services.
Now our socket server can create multiple threads as needed. Once an object is accepted
on the port (port 3000 in our case), which happens in the run method, the execCmdObject
method is called. This method is a big switch statement. It inspects the command object for the
action to be performed and then calls the matching method in DVDDatabase . Refer to the proj-
ect download for the entire DBSocketRequest class. For brevity, Listing 7-3 only shows the run
method.
Listing 7-3. DBSocketRequest.java
/**
* Required for a class that extends thread, this is the main path
* of execution for this thread.
public void run() {
try {
ObjectOutputStream out =
new ObjectOutputStream(client.getOutputStream());
ObjectInputStream in =
new ObjectInputStream(client.getInputStream());
DVDCommand cmdObj = (DVDCommand) in.readObject();
out.writeObject(execCmdObject(cmdObj));
if (client != null) {
client.close();
}
out.flush();
}
catch (SocketException e) {
logger.log(Level.SEVERE,
"SocketException in Socket Server: " + e.getMessage());
}
catch (Exception e) {
logger.log(Level.SEVERE,
"General Exception in Socket Server: "
+ e.getMessage()
);
}
Search WWH ::




Custom Search