Java Reference
In-Depth Information
et
instance,addsthe
Connection
objecttothe
clients
array,startsthe
Connec-
tion
thread,andsendsagreetingmessagetotheclientassociatedwiththe
Connec-
tion
object's socket.
When the
Connection
thread's
run()
method starts running, it first obtains the
client'sname(thenameoftheuserrunningtheclientapplication)viaa
readLine()
methodcall.Ittheninvokes
Connection
's
void sendClientsList()
method
to notify all clients about the latest client to join the chat.
sendClientsList()
provides this notification by first building an exclamation
mark(!)-prefixedstringofspace-separatedclientnames,andtheninvoking
Connec-
tion
's
void broadcast(String message)
methodtobroadcastthisstringto
all clients participating in the chat.
Inturn,
broadcast()
invokes
Connection
's
void send(message)
method
on each
Connection
object stored in the
clients
array.
The
Connection
thread's
run()
method then enters a loop that uses
readLine()
to read each line from the client, and then broadcasts this line with the
client name as a prefix to all clients.
At some point, the client's socket will be closed when its user chooses to quit the
chat.Thisactcauses
readLine()
toreturnnull,whichendstheloopandcausesthe
trystatement'sfinallyclausetoexecute.Thisclauseremovestheclient's
Connection
object from the
clients
array and broadcasts messages that identify the number of
remaining clients and their names.
Although
ChatServer
is conceptually simple, its use of
volatile
and thread
synchronization make it appear more difficult.
Ideclareavariable
volatile
whereveritcanbeaccessedbymultiplethreads.The
idea is to ensure that
ChatServer
will work on multicore/multiprocessor machines
that contain separated cached copies of the variable.
Iusesynchronizationtoensurethatclientshaveaconsistentviewofthechatserver's
state. For example,
runServer()
executes
clients.add(con);
through
con.send("welcome...you're the latest of "+clients.size()+"
users");
inasynchronizedblock,andalsoexecutes
clients.remove(this);
through
sendClientsList();
inanothersynchronizedblockthatsynchronizeson
thesame
clients
object,sothataclientcannotberemovedinbetweenaclientbeing
addedandamessagesenttothatclientaboutthecurrentnumberofclients,andalsoso
thataclientcannotbeaddedinbetweenaclientbeingremovedandallremainingclients
being notified about the current number of clients.