(Ebook) Java Network Programming by Elliotte Rusty Harold ISBN 9781449357672, 1449357679 - The ebook in PDF format with all chapters is ready for download
(Ebook) Java Network Programming by Elliotte Rusty Harold ISBN 9781449357672, 1449357679 - The ebook in PDF format with all chapters is ready for download
https://ebooknice.com/product/java-network-programming-55585978
https://ebooknice.com/product/java-network-programming-third-
edition-2332242
https://ebooknice.com/product/java-i-o-38436468
https://ebooknice.com/product/xml-bible-923002
(Ebook) XML Bible, Gold Edition by Elliotte Rusty Harold ISBN
9780764548192, 0764548190
https://ebooknice.com/product/xml-bible-gold-edition-1927878
https://ebooknice.com/product/xml-1-1-bible-922998
https://ebooknice.com/product/xml-in-a-nutshell-5065374
https://ebooknice.com/product/learning-network-programming-with-
java-55588204
https://ebooknice.com/product/learning-network-programming-with-
java-38073304
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
Random documents with unrelated
content Scribd suggests to you:
l'opinion des physiciens, qui pensent que les trombes ne sont qu'un
phénomène électrique.
Quoi qu'il en puisse être de ces définitions différentes, il est un
fait que personne ne peut méconnaître ni contester: c'est que les
parages dans lesquels on observe le plus souvent la présence des
trombes de mer, sont ceux où de brusques changemens de vents, et
le renversement subit de brises ou de moussons, se font sentir avec
le plus de fréquence et de force.
Tels sont les parages du golfe de Guinée, le canal Mozambique,
les Moluques, les Philippines, etc.
Les trombes marines, qui furent pendant si long-temps un grand
sujet d'effroi pour nos vieux navigateurs, paraissent avoir perdu
aujourd'hui, comme toutes les choses que l'on croit voir de près, une
partie du prestige qui les faisait tant redouter autrefois. L'aspect
d'une trombe semblait menacer d'un anéantissement total le navire
assez malheureux pour rencontrer ce spectre des mers. Un coup de
canon envoyé à boulet sur la fantastique colonne d'eau pouvait,
disait-on, faire s'écrouler sur lui-même ce colosse redoutable des
élémens conjurés. Aussi, les anciens bâtimens du commerce
n'embarquaient-ils une ou deux mauvaises pièces d'artillerie à leur
bord, que pour crever une trombe, ou pour appeler à eux les pilotes
dans les momens de détresse, car le naufrage et les trombes étaient
les deux plus grands dangers que pouvaient craindre les navigateurs
des siècles passés.
Mais, maintenant que l'expérience a réduit, en quelque sorte, les
trombes de mer à leur juste valeur, on sait les effets qu'elles sont
capables de produire sur les navires qui se trouvent exposés à les
recevoir en mer. Plusieurs grands bâtimens ayant été assaillis par ces
énormes nuées d'eau ascendantes, en ont été quittes pour avoir vu
le tourbillon liquide enlever leurs voiles, une partie de la mâture, et
des objets amarrés sur le pont; accident toujours grave il est vrai,
mais moins effrayant encore que la destruction totale dont,
autrefois, l'approche d'une trombe marine paraissait menacer les
navires mêmes du plus fort tonnage et de la plus grande solidité.
La manière dont je m'y prends pour mettre dans la bouche de
maître Bastringue la description d'une trombe marine, ne peut
amener sans doute qu'une idée très imparfaite de la théorie aux
raisons de laquelle il est possible d'expliquer ou de définir ces sortes
de phénomènes. Mais pour rendre l'effet que produit en général sur
l'esprit des matelots, l'aspect d'une trombe, il fallait bien faire parler
un marin autrement que n'aurait parlé un savant de l'Institut, qui
aurait observé, par ordre de l'Académie, l'apparition du météore dont
il est question dans ce chapitre. Les hommes du commun et les
hommes de la science, ont les mêmes yeux, mais ils n'ont ni les
mêmes idées, sur les choses qui affectent leurs yeux, ni les mêmes
expressions pour rendre les idées que la vue des mêmes objets peut
produire sur leur imagination. Or, ce qu'il y a de plus piquant pour
les gens du monde, ce n'est guère d'apprendre la manière dont s'y
prendrait un savant pour rendre compte des sensations que lui ferait
éprouver l'apparition d'une chose extraordinaire. Il y a long-temps
que l'on sait que les personnes instruites n'ont qu'un langage pour
peindre ce qu'elles observent dans l'intérêt de la science; et
malheureusement, la préoccupation à laquelle elles sont presque
toujours livrées dans l'ardeur de leurs recherches méthodiques, ne
laisse que trop peu de part à cette mobilité d'impressions, que l'on
aime à retrouver dans la peinture des événemens saisissans. Or, le
langage le plus propre peut-être à rendre fidèlement et
énergiquement les impressions les plus vives, et je l'avouerai à ma
honte et à la honte de notre langue littéraire, est le langage, ou si
l'on veut, le jargon que parlent les hommes du peuple. Cette
observation est si désespérante, et si vraie en même temps, que
pour décrire les combats, les manœuvres et les tempêtes, toutes
choses fort émouvantes de leur nature, le style officiel du bulletin et
le style même de l'histoire, a été obligé d'emprunter au langage
vulgaire des soldats et des matelots, les termes avec lesquels il
devenait possible de rendre certaines idées, et de peindre certains
faits. Dumarsais a dit, avec sa haute et profonde raison, qu'il se
faisait plus de figures un jour de marché, à la halle, qu'il ne s'en
faisait en plusieurs jours d'assemblées académiques. On pourrait
encore ajouter pour compléter le sens de cette assertion, que les
plus belles figures de rhétorique que nos écrivains aient mises
littérairement en œuvre, n'ont pu être empruntées qu'à la rhétorique
naturelle des gens qui savent le moins bien exprimer des idées
communes.
[2] Les vœux d'une nature au moins aussi étrange que celui que
je mets ici sur le compte de maître Bastringue, n'étaient pas rares
chez les anciens marins livrés pour la plupart à la superstition des
temps dans lesquels ils vivaient; et, pour prouver jusqu'à quel point
peut aller quelquefois la bizarrerie des engagemens qu'ils prenaient
avec le ciel dans les momens de péril et d'effroi, je me contenterai
de citer un exemple qui, je crois, pourra me dispenser de reproduire,
à l'appui de la vraisemblance du fait que j'ai cité dans ce chapitre,
les autres témoignages que je serais encore à même d'invoquer en
recueillant mes souvenirs.
Un capitaine caboteur, assailli par une tempête qui menaçait
d'envahir à chaque lame, son malheureux petit navire, promit à la
Vierge-Marie, de retirer du péché la première fille de joie qu'il
rencontrerait à terre, s'il parvenait jamais à rentrer sain et sauf dans
le port. Le miracle se fit, et le navire fut sauvé. Le dévôt capitaine ne
tarda pas à trouver l'occasion de se montrer fidèle au vœu qu'il avait
formé dans le danger, et, en arrivant pieds nus à terre, pour aller
déposer un cierge bénit sur l'autel de la secourable Madone, il
rencontra sur son chemin la femme qu'il s'était engagé à retirer des
abîmes du vice. C'était, entre toutes les pécheresses du lieu dans
lequel le capitaine avait été chercher un refuge, la fille la plus
connue et la plus mal famée, et cette circonstance, en donnant plus
d'éclat au sacrifice du marin, devait lui rendre ce sacrifice plus
méritoire, et son devoir plus sacré. Il épousa sa nouvelle et facile
conquête en donnant à la cérémonie de son mariage tout le
pompeux scandale qu'il jugeait le plus propre à sanctifier son
humilité. Mais, ce qu'il y a de plus extraordinaire dans cette
inconcevable aventure, c'est que la Madelaine ainsi purifiée par les
chastes feux de l'hyménée, devint aussi sage qu'elle avait été
autrefois dissolue, et que son pieux époux finit par mourir
d'ivrognerie dans un des lieux de prostitution, d'où il avait si
évangéliquement retiré sa fiancée.
«Enfans de l'Aventure,
«Vous aurez des femmes, comme s'il en fusillait dans le
pays; mais pas celles des autorités, ni des habitans. Vous
pourrez les battre, mais en payant. Chacun de vous va recevoir,
à la chambre, vingt-cinq gourdes d'avances, sur ses parts de
prise à venir, et tout le monde, indistinctement, ira ensuite à
terre, s'amuser pendant trois jours, tant qu'il voudra, et comme
il pourra. Mais, au bout de ce temps de jouisserie générale, et
au moment de l'appareillage, il est bon de vous prévenir, que le
premier qui reviendra à bord avec un sou, seulement, dans la
poche, me fera l'honneur d'avoir affaire à moi, et vous savez
tous, que je ne m'appelle pas Malviré pour des prunes de Tours,
et pour faire l'amour avec vous autres, quand le cœur ne m'en
dit pas! Salut à vous! C'est là tout ce que j'avais à vous confier.
Valsez!»
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.
ebooknice.com