A Multiplexed Network Client
We end this chapter with Example 6-14, a complex class
named HttpDownloadManager
. As its
name implies, this class is a client-side utility that manages any
number of concurrent HTTP downloads on a background thread. To
download something, just call the download(
)
method, passing a java.net.URI
and an optional Listener
object to be notified when the
download is complete or has aborted with an error. download( )
does not block: it returns a
Download
object immediately, and
you can monitor the status of the download by polling the methods of
this object. The data that is downloaded is not saved to a file, but
is available from the getData( )
method of the Download
object.
The Listener
and Download
interfaces are defined as inner
classes of HttpDownloadManager
. The
Status
class is another inner
class: it is a type-safe enumeration of download states returned by
Download.getStatus( )
. Two other
inner classes used in this example are DownloadImpl
, the package-private concrete
implementation of the Download
interface, and Test
, a simple test
program that demonstrates the usage of the HttpDownloadManager
.
HttpDownloadManager
extends
Thread
, and the downloads are
handled in this background thread. Multiple downloads can be handled
concurrently (this is useful when the client has more bandwidth
available than the servers which are being downloaded from) because
the thread uses a Selector
to
multiplex the SocketChannel
objects from which data is being read: the ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.