Java Reference
In-Depth Information
Exercises
3.1 Take a copy of example ThreadHelloCount (Sect. 3.2.1 ). Examine the code
and then compile and run the program, observing the results.
3.2 Modify the above code to use the alternative method for multithreading (i.e.,
implementing the Runnable interface). Name your main class RunnableHelloBye
and your subsidiary classes Hello and Goodbye respectively. The fi rst should
display the message 'Hello!' ten times (with a random delay of 0-2 s between
consecutive displays), while the second should do the same with the message
'Goodbye!'.
Note that it will NOT be the main class that implements the Runnable
interface, but each of the two subsidiary classes.
3.3 Take a copy of ResourceServer (Sect. 3.5 ), examine the code and run the
program.
3.4 Take a copy of MultiEchoClient (Sect. 3.3 ), re-naming it ConsumerClient .
Using this fi le as a template, modify the code so that the program acts as a cli-
ent of ResourceServer , as shown in the screenshots at the end of Sect. 3.5 .
(Ensure that the user can pass only 0 or 1 to the server.) Test the operation of
the server with two clients.
Note that exercises 3.5 and 3.6 (especially the latter) are rather substantial tasks.
3.5 Implement a basic electronic chatroom application that employs a multithreaded
server. Both server and client will need to be implemented and brief details of
these programs are provided below.
The multithreaded chat server must broadcast each message it receives to all
the connected clients, of course. It should also maintain a dynamic list of Socket
references associated with those clients. Though you could use an array to hold
the list (with an appropriate over-allocation of array cells, to cater for a poten-
tially large number of connections), the use of a Vector object would be much
more realistic. (If you are unfamiliar with Vector s, then refer to Sect. 4.8 in the
next chapter.)
The client must be implemented as a GUI that can send and receive mes-
sages until it sends the string 'Bye'. A separate thread will be required to
receive messages from the server and add them cumulatively to a text area. The
fi rst two things that this thread should do are (i) accept the user's chatroom
nickname (probably via an input dialogue box) and (ii) send this name to the
server. All other messages should be sent via a text area and associated button.
As a simplifi cation, assume that no two clients will select the same nickname.
Note
It is likely that a NoSuchElementException will be generated at the line that reads
from the socket's input stream when the user's socket is closed (after sending
'Bye'), so place this reading line inside a try and have an empty catch .
Search WWH ::




Custom Search