Instant Download Java Network Programming Fourth Edition Harold Elliotte PDF All Chapters
Instant Download Java Network Programming Fourth Edition Harold Elliotte PDF All Chapters
com
https://textbookfull.com/product/java-network-programming-
fourth-edition-harold-elliotte/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/learning-network-programming-with-
java-1st-edition-reese-richard-m/
textboxfull.com
https://textbookfull.com/product/java-programming-joyce-farrell/
textboxfull.com
https://textbookfull.com/product/java-programming-joyce-farrell-2/
textboxfull.com
Java pocket guide Fourth Edition Robert Liguori
https://textbookfull.com/product/java-pocket-guide-fourth-edition-
robert-liguori/
textboxfull.com
https://textbookfull.com/product/programming-in-java-sachin-malhotra/
textboxfull.com
https://textbookfull.com/product/python-network-programming-cookbook-
kathiravelu/
textboxfull.com
https://textbookfull.com/product/comptia-network-review-guide-fourth-
edition-edition-craig-zacker/
textboxfull.com
https://textbookfull.com/product/learning-java-beginning-programming-
with-java-for-dummies-first-edition-john-bach/
textboxfull.com
FOURTH EDITION
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Java Network Programming, the image of a North American river otter, and related trade dress
are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐
mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-449-35767-2
[LSI]
This book is dedicated to my dog, Thor.
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
2. Streams. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Output Streams 26
Input Streams 31
Marking and Resetting 34
Filter Streams 35
Chaining Filters Together 37
Buffered Streams 38
v
PrintStream 39
Data Streams 41
Readers and Writers 44
Writers 45
OutputStreamWriter 47
Readers 47
Filter Readers and Writers 49
PrintWriter 51
3. Threads. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Running Threads 55
Subclassing Thread 56
Implementing the Runnable Interface 58
Returning Information from a Thread 60
Race Conditions 61
Polling 63
Callbacks 63
Futures, Callables, and Executors 68
Synchronization 70
Synchronized Blocks 72
Synchronized Methods 74
Alternatives to Synchronization 75
Deadlock 77
Thread Scheduling 78
Priorities 78
Preemption 79
Thread Pools and Executors 89
4. Internet Addresses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
The InetAddress Class 95
Creating New InetAddress Objects 95
Getter Methods 100
Address Types 102
Testing Reachability 106
Object Methods 106
Inet4Address and Inet6Address 107
The NetworkInterface Class 108
Factory Methods 108
Getter Methods 110
Some Useful Programs 111
SpamCheck 111
vi | Table of Contents
Processing Web Server Logfiles 112
6. HTTP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
The Protocol 169
Keep-Alive 175
HTTP Methods 177
The Request Body 179
Cookies 181
CookieManager 184
CookieStore 185
7. URLConnections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Opening URLConnections 188
Table of Contents | ix
Configuring SSLServerSockets 343
Choosing the Cipher Suites 343
Session Management 344
Client Mode 344
x | Table of Contents
SO_TIMEOUT 417
SO_RCVBUF 418
SO_SNDBUF 419
SO_REUSEADDR 419
SO_BROADCAST 419
IP_TOS 420
Some Useful Applications 421
Simple UDP Clients 421
UDPServer 425
A UDP Echo Client 428
DatagramChannel 431
Using DatagramChannel 431
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
Table of Contents | xi
Preface
Java’s growth over the past 20 years has been nothing short of phenomenal. Given Java’s
rapid rise to prominence and the even more spectacular growth of the Internet, it’s a
little surprising that network programming in Java remains so mysterious to so many.
It doesn’t have to be. In fact, writing network programs in Java is quite simple, as this
book will show. Readers with previous experience in network programming in a Unix,
Windows, or Macintosh environment will be pleasantly surprised at how much easier
it is to write equivalent programs in Java. The Java core API includes well-designed
interfaces to most network features. Indeed, there is very little application layer network
software you can write in C or C++ that you can’t write more easily in Java. Java Network
Programming, Fourth Edition, endeavors to show you how to take advantage of Java’s
network class library to quickly and easily write programs that accomplish many com‐
mon networking tasks. Some of these include:
Java is the first (though no longer the only) language to provide such a powerful cross-
platform network library for handling all these diverse tasks. Java Network Program‐
ming exposes the power and sophistication of this library. This book’s goal is to enable
xiii
you to start using Java as a platform for serious network programming. To do so, this
book provides a general background in network fundamentals, as well as detailed dis‐
cussions of Java’s facilities for writing network programs. You’ll learn how to write Java
programs that share data across the Internet for games, collaboration, software updates,
file transfer, and more. You’ll also get a behind-the-scenes look at HTTP, SMTP,
TCP/IP, and the other protocols that support the Internet and the Web. When you finish
this book, you’ll have the knowledge and the tools to create the next generation of
software that takes full advantage of the Internet.
xiv | Preface
The next two chapters throw some light on two parts of Java programming that are
critical to almost all network programs but are often misunderstood and misused: I/O
and threading. Chapter 2, Streams, explores Java’s classic I/O which—despite the new
I/O APIs—isn’t going away any time soon and is still the preferred means of handling
input and output in most client applications. Understanding how Java handles I/O in
the general case is a prerequisite for understanding the special case of how Java handles
network I/O. Chapter 3, Threads, explores multithreading and synchronization, with a
special emphasis on how they can be used for asynchronous I/O and network servers.
Experienced Java programmers may be able to skim or skip these two chapters. However,
Chapter 4, Internet Addresses, is essential reading for everyone. It shows how Java pro‐
grams interact with the Domain Name System through the InetAddress class, the one
class that’s needed by essentially all network programs. Once you’ve finished this chap‐
ter, it’s possible to jump around in the book as your interests and needs dictate.
Chapter 5, URLs and URIs, explores Java’s URL class, a powerful abstraction for down‐
loading information and files from network servers of many kinds. The URL class enables
you to connect to and download files and documents from a network server without
concerning yourself with the details of the protocol the server speaks. It lets you connect
to an FTP server using the same code you use to talk to an HTTP server or to read a file
on the local hard disk. You’ll also learn about the newer URI class, a more standards-
conformant alternative for identifying but not retrieving resources.
Chapter 6, HTTP, delves deeper into the HTTP protocol specifically. Topics covered
include REST, HTTP headers, and cookies. Chapter 7, URLConnections, shows you how
to use the URLConnection and HttpURLConnection classes not just to download data
from web servers, but to upload documents and configure connections.
Chapter 8 through Chapter 10 discuss Java’s low-level socket classes for network access.
Chapter 8, Sockets for Clients, introduces the Java sockets API and the Socket class in
particular. It shows you how to write network clients that interact with TCP servers of
all kinds including whois, dict, and HTTP. Chapter 9, Sockets for Servers, shows you
how to use the ServerSocket class to write servers for these and other protocols. Finally,
Chapter 10, Secure Sockets, shows you how to protect your client-server communica‐
tions using the Secure Sockets Layer (SSL) and the Java Secure Sockets Extension (JSSE).
Chapter 11, Nonblocking I/O, introduces the new I/O APIs specifically designed for
network servers. These APIs enable a program to figure out whether a connection is
ready before it tries to read from or write to the socket. This allows a single thread to
manage many different connections simultaneously, thereby placing much less load on
the virtual machine. The new I/O APIs don’t help much for small servers or clients that
don’t open many simultaneous connections, but they may provide performance boosts
for high-volume servers that want to transmit as much data as the network can handle
as fast as the network can deliver it.
Preface | xv
Chapter 12, UDP, introduces the User Datagram Protocol (UDP) and the associated
DatagramPacket and DatagramSocket classes that provide fast, unreliable communi‐
cation. Finally, Chapter 13, IP Multicast, shows you how to use UDP to communicate
with multiple hosts at the same time.
Java Versions
Java’s network classes have changed a lot more slowly since Java 1.0 than other parts of
the core API. In comparison to the AWT or I/O, there have been almost no changes and
only a few additions. Of course, all network programs make extensive use of the I/O
classes and some make heavy use of GUIs. This book is written with the assumption
that you are coding with at least Java 5.0. In general, I use Java 5 features like generics
and the enhanced for loop freely without further explanation.
For network programming purposes, the distinction between Java 5 and Java 6 is not
large. Most examples look identical in the two versions. When a particular method or
class is new in Java 6, 7, or 8, it is noted by a comment following its declaration like this:
public void setFixedLengthStreamingMode(long contentLength) // Java 7
Java 7 is a bit more of a stretch. I have not shied away from using features introduced
in Java 7 where they seemed especially useful or convenient—for instance, try-with-
resources and multicatch are both very helpful when trying to fit examples into the
limited space available in a printed book—but I have been careful to point out my use
of such features.
Overall, though, Java’s networking API has been relatively stable since Java 1.0. Very
little of the post-1.0 networking API has ever been deprecated, and additions have been
xvi | Preface
relatively minor. You shouldn’t have any trouble using this book after Java 8 is released.
New APIs, however, have been somewhat more frequent in the supporting classes, par‐
ticularly I/O, which has undergone three major revisions since Java 1.0.
Preface | xvii
Conventions Used in This Book
Body text is Minion Pro, normal, like you’re reading now.
A monospaced typewriter font is used for:
• Command lines and options that should be typed verbatim on the screen
Significant code fragments and complete programs are generally placed into a separate
paragraph, like this:
Socket s = new Socket("java.oreilly.com", 80);
if (!s.getTcpNoDelay()) s.setTcpNoDelay(true);
xviii | Preface
When code is presented as fragments rather than complete programs, the existence of
the appropriate import statements should be inferred. For example, in the preceding
code fragment you may assume that java.net.Socket was imported.
Some examples intermix user input with program output. In these cases, the user input
will be displayed in bold, as in this example from Chapter 9:
% telnet rama.poly.edu 7
Trying 128.238.10.212...
Connected to rama.poly.edu.
Escape character is '^]'.
This is a test
This is a test
This is another test
This is another test
9876543210
9876543210
^]
telnet> close
Connection closed.
Finally, although many of the examples used here are toy examples unlikely to be reused,
a few of the classes I develop have real value. Please feel free to reuse them or any parts
of them in your own code. No special permission is required. They are in the public
domain (although the same is most definitely not true of the explanatory text!).
Preface | xix
worked on this book, I’m sure there are mistakes and typographical errors that we missed
here somewhere. And I’m sure that at least one of them is a really embarrassing whopper
of a problem. If you find a mistake or a typo, please let me know so I can correct it. I’ll
post it on the O’Reilly website at http://oreil.ly/java_np_errata. Before reporting errors,
please check one of those pages to see if I already know about it and have posted a fix.
Any errors that are reported will be fixed in future printings.
xx | Preface
ogy, and dozens more. For more information about Safari Books Online, please visit us
online.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/java-network-prgamming.
To comment or ask technical questions about this book, send email to bookques
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
Many people were involved in the production of this book. My editor, Mike Loukides,
got things rolling, and provided many helpful comments along the way that substantially
improved the book. Dr. Peter “Peppar” Parnes helped out immensely with Chapter 13.
The technical editors all provided invaluable assistance in hunting down errors and
omissions. Simon St. Laurent provided crucial advice on which topics deserved more
coverage. Scott Oaks lent his thread expertise to Chapter 3, proving once again by the
many subtle bugs he hunted down that multithreading still requires the attention of an
expert. Ron Hitchens shone light into many of the darker areas of the new I/O APIs.
Marc Loy and Jim Elliott reviewed some of the most bleeding edge material in the book.
Timothy F. Rohaly was unswerving in his commitment to making sure I closed all my
sockets and caught all possible exceptions, and in general wrote the cleanest, safest, most
exemplary code I could write. John Zukowski found numerous errors of omission, all
now filled thanks to him. And the eagle-eyed Avner Gelb displayed an astonishing ability
to spot mistakes that had somehow managed to go unnoticed by myself, all the other
Preface | xxi
editors, and the tens of thousands of readers of the first edition. Alex Stangl and Ryan
Cuprak provided further assistance with spotting both new and lingering mistakes in
this latest edition.
It isn’t customary to thank the publisher, but the publisher does set the tone for the rest
of the company, authors, editors, and production staff alike; and I think Tim O’Reilly
deserves special credit for making O’Reilly Media absolutely one of the best houses an
author can write for. If there’s one person without whom this book would never have
been written, it’s him. If you, the reader, find O’Reilly books to be consistently better
than most of the dreck on the market, the reason really can be traced straight back to
Tim.
My agent, David Rogelberg, convinced me it was possible to make a living writing books
like this rather than working in an office. The entire crew at ibiblio.org over the last
several years has really helped me to communicate better with my readers in a variety
of ways. Every reader who sent in bouquets and brickbats for previous editions has been
instrumental in helping me write this much-improved edition. All these people deserve
much thanks and credit. Finally, as always, I’d like to offer my largest thanks to my wife,
Beth, without whose love and support this book would never have happened.
—Elliotte Rusty Harold
elharo@ibiblio.org
July 5, 2013
xxii | Preface
CHAPTER 1
Basic Network Concepts
• Text editors like BBEdit save and open files directly from FTP servers.
• IDEs like Eclipse and IntelliJ IDEA communicate with source code repositories like
GitHub and Sourceforge.
• Word processors like Microsoft Word open files from URLs.
• Antivirus programs like Norton AntiVirus check for new virus definitions by con‐
necting to the vendor’s website every time the computer is started.
• Music players like Winamp and iTunes upload CD track lengths to CDDB and
download the corresponding track titles.
• Gamers playing multiplayer first-person shooters like Halo gleefully frag each other
in real time.
• Supermarket cash registers running IBM SurePOS ACE communicate with their
store’s server in real time with each transaction. The server uploads its daily receipts
to the chain’s central computers each night.
• Schedule applications like Microsoft Outlook automatically synchronize calendars
among employees in a company.
Java was the first programming language designed from the ground up for network
applications. Java was originally aimed at proprietary cable television networks rather
than the Internet, but it’s always had the network foremost in mind. One of the first two
real Java applications was a web browser. As the Internet continues to grow, Java is
uniquely suited to build the next generation of network applications.
1
One of the biggest secrets about Java is that it makes writing network programs easy. In
fact, it is far easier to write network programs in Java than in almost any other language.
This book shows you dozens of complete programs that take advantage of the Internet.
Some are simple textbook examples, while others are completely functional applica‐
tions. One thing you’ll notice in the fully functional applications is just how little code
is devoted to networking. Even in network-intensive programs like web servers and
clients, almost all the code handles data manipulation or the user interface. The part of
the program that deals with the network is almost always the shortest and simplest. In
brief, it is easy for Java applications to send and receive data across the Internet.
This chapter covers the background networking concepts you need to understand be‐
fore writing networked programs in Java (or, for that matter, in any language). Moving
from the most general to the most specific, it explains what you need to know about
networks in general, IP and TCP/IP-based networks in particular, and the Internet. This
chapter doesn’t try to teach you how to wire a network or configure a router, but you
will learn what you need to know to write applications that communicate across the
Internet. Topics covered in this chapter include the nature of networks; the TCP/IP layer
model; the IP, TCP, and UDP protocols; firewalls and proxy servers; the Internet; and
the Internet standardization process. Experienced network gurus may safely skip this
chapter, and move on to the next chapter where you begin developing the tools needed
to write your own network programs in Java.
Networks
A network is a collection of computers and other devices that can send data to and
receive data from one another, more or less in real time. A network is often connected
by wires, and the bits of data are turned into electromagnetic waves that move through
the wires. However, wireless networks transmit data using radio waves; and most long-
distance transmissions are now carried over fiber-optic cables that send light waves
through glass filaments. There’s nothing sacred about any particular physical medium
for the transmission of data. Theoretically, data could be transmitted by coal-powered
computers that send smoke signals to one another. The response time (and environ‐
mental impact) of such a network would be rather poor.
Each machine on a network is called a node. Most nodes are computers, but printers,
routers, bridges, gateways, dumb terminals, and Coca-Cola™ machines can also be no‐
des. You might use Java to interface with a Coke machine, but otherwise you’ll mostly
talk to other computers. Nodes that are fully functional computers are also called
hosts. I will use the word node to refer to any device on the network, and the word host
to refer to a node that is a general-purpose computer.
Every network node has an address, a sequence of bytes that uniquely identifies it. You
can think of this group of bytes as a number, but in general the number of bytes in an
address or the ordering of those bytes (big endian or little endian) is not guaranteed to
Networks | 3
servers communicate; at the other end of the spectrum, the IEEE 802.3 standard defines
a protocol for how bits are encoded as electrical signals on a particular type of wire.
Open, published protocol standards allow software and equipment from different ven‐
dors to communicate with one another. A web server doesn’t care whether the client is
a Unix workstation, an Android phone, or an iPad, because all clients speak the same
HTTP protocol regardless of platform.
There are several different layer models, each organized to fit the needs of a particular
kind of network. This book uses the standard TCP/IP four-layer model appropriate for
the Internet, shown in Figure 1-2. In this model, applications like Firefox and Warcraft
run in the application layer and talk only to the transport layer. The transport layer talks
only to the application layer and the Internet layer. The Internet layer in turn talks only
to the host-to-network layer and the transport layer, never directly to the application
layer. The host-to-network layer moves the data across the wires, fiber-optic cables, or
other medium to the host-to-network layer on the remote system, which then moves
the data up the layers to the application on the remote system.
For example, when a web browser sends a request to a web server to retrieve a page, the
browser is actually talking to the transport layer on the local client machine. The trans‐
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com