Java Reference
In-Depth Information
/** Before a client breaks off, remove it from the list. **/
public synchronized void clientDisconnected (String user,
DataWorker worker) {
println ("Client: " + user + "disconneced");
fWorkerList.remove (worker);
fClientCounter
--
-;
}
The
DataServer
hands off the client socket to
DataWorker
and then the
worker begins its job of communicating with the client and providing it the
requested services.
15.5 The
DataWorker
The
DataWorker
is a thread that tends to the needs of its client. It maintains the
connection until the client breaks it. The worker calls back to the
DataServer
to add or subtract itself to the list of workers and to send messages for display in
the text area in the server's user interface. The worker follows a simple protocol
with the client so that each knows when to send a message and when to wait for
a message (and when to send or receive numerical values). The server initially
carries out a simple log-in procedure, which here just means a request for a
user name. As we mentioned earlier, you could easily expand this to include a
password exchange as well.
As shown in the following code snippet, the first act by the
run()
method is to
invoke the
serviceSetup()
method. This method sets up the streams for I/O
with the client. The
PrintWriter
and
BufferedReader
wrappers are used
to send and receive text to and from the client. A
DataOutputStream
wrapper
is used to send numerical values. The read/write methods for these streams are
put into some utility methods discussed later.
If the maximum number of clients has been reached, the worker sends a warn-
ing message to its client and breaks off the connection. That worker thread itself
then signs off from the server and dies.
If there is room for the client, the
serviceSetup()
method performs
a simple log-in procedure with the client that consists of sending the string
“
Username:
„
to the client and waiting for a string in return:
...
The
run()
and serviceSetup() methods in the class
DataWorker
...
public void run () {
// If service setup fails, end thread processing.
if (!serviceSetup ()) return;
...
Search WWH ::
Custom Search