SlideShare a Scribd company logo
Java Network Programming Fourth Edition Harold
Elliotte pdf download
https://textbookfull.com/product/java-network-programming-fourth-
edition-harold-elliotte/
Download more ebook from https://textbookfull.com
We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!
Learning Network Programming with Java 1st Edition
Reese Richard M
https://textbookfull.com/product/learning-network-programming-
with-java-1st-edition-reese-richard-m/
Neural Network Programming with Java Create and unleash
the power of neural networks by implementing
professional Java code 1st Edition Souza
https://textbookfull.com/product/neural-network-programming-with-
java-create-and-unleash-the-power-of-neural-networks-by-
implementing-professional-java-code-1st-edition-souza/
Java Programming Joyce Farrell
https://textbookfull.com/product/java-programming-joyce-farrell/
Java Programming Joyce Farrell
https://textbookfull.com/product/java-programming-joyce-
farrell-2/
Java pocket guide Fourth Edition Robert Liguori
https://textbookfull.com/product/java-pocket-guide-fourth-
edition-robert-liguori/
Programming in Java Sachin Malhotra
https://textbookfull.com/product/programming-in-java-sachin-
malhotra/
Python Network Programming Cookbook Kathiravelu
https://textbookfull.com/product/python-network-programming-
cookbook-kathiravelu/
CompTIA Network Review Guide Fourth Edition. Edition
Craig Zacker
https://textbookfull.com/product/comptia-network-review-guide-
fourth-edition-edition-craig-zacker/
Learning Java Beginning programming with java for
dummies First Edition John Bach
https://textbookfull.com/product/learning-java-beginning-
programming-with-java-for-dummies-first-edition-john-bach/
Java Network Programming Fourth Edition Harold Elliotte
Java Network Programming Fourth Edition Harold Elliotte
Elliotte Rusty Harold
FOURTH EDITION
Java Network Programming
Java Network Programming, Fourth Edition
by Elliotte Rusty Harold
Copyright © 2014 Elliotte Rusty Harold. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
alsoavailableformosttitles(http://my.safaribooksonline.com).Formoreinformation,contactourcorporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editor: Meghan Blanchette
Production Editor: Nicole Shelby
Copyeditor: Kim Cofer
Proofreader: Jasmine Kwityn
Indexer: Judy McConville
Cover Designer: Randy Comer
Interior Designer: David Futato
Illustrator: Rebecca Demarest
October 2013: Fourth Edition
Revision History for the Fourth Edition:
2013-09-23: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781449357672 for release details.
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.
Java Network Programming Fourth Edition Harold Elliotte
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
1. Basic Network Concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Networks 2
The Layers of a Network 4
The Host-to-Network Layer 7
The Internet Layer 8
The Transport Layer 9
The Application Layer 10
IP, TCP, and UDP 10
IP Addresses and Domain Names 11
Ports 13
The Internet 14
Internet Address Blocks 15
Network Address Translation 15
Firewalls 15
Proxy Servers 16
The Client/Server Model 18
Internet Standards 19
IETF RFCs 20
W3C Recommendations 22
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
5. URLs and URIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
URIs 117
URLs 120
Relative URLs 122
The URL Class 123
Creating New URLs 123
Retrieving Data from a URL 128
Splitting a URL into Pieces 135
Equality and Comparison 139
Conversion 141
The URI Class 141
Constructing a URI 142
The Parts of the URI 144
Resolving Relative URIs 147
Equality and Comparison 148
String Representations 149
x-www-form-urlencoded 149
URLEncoder 150
URLDecoder 154
Proxies 154
System Properties 155
The Proxy Class 155
The ProxySelector Class 156
Communicating with Server-Side Programs Through GET 157
Accessing Password-Protected Sites 161
The Authenticator Class 162
The PasswordAuthentication Class 164
The JPasswordField Class 164
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 | vii
Reading Data from a Server 189
Reading the Header 190
Retrieving Specific Header Fields 191
Retrieving Arbitrary Header Fields 197
Caches 199
Web Cache for Java 203
Configuring the Connection 208
protected URL url 209
protected boolean connected 209
protected boolean allowUserInteraction 210
protected boolean doInput 211
protected boolean doOutput 212
protected boolean ifModifiedSince 212
protected boolean useCaches 214
Timeouts 215
Configuring the Client Request HTTP Header 215
Writing Data to a Server 218
Security Considerations for URLConnections 223
Guessing MIME Media Types 224
HttpURLConnection 224
The Request Method 225
Disconnecting from the Server 229
Handling Server Responses 230
Proxies 235
Streaming Mode 235
8. Sockets for Clients. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Using Sockets 237
Investigating Protocols with Telnet 238
Reading from Servers with Sockets 240
Writing to Servers with Sockets 246
Constructing and Connecting Sockets 251
Basic Constructors 251
Picking a Local Interface to Connect From 253
Constructing Without Connecting 254
Socket Addresses 255
Proxy Servers 256
Getting Information About a Socket 257
Closed or Connected? 258
toString() 259
Setting Socket Options 259
TCP_NODELAY 260
viii | Table of Contents
SO_LINGER 261
SO_TIMEOUT 261
SO_RCVBUF and SO_SNDBUF 262
SO_KEEPALIVE 263
OOBINLINE 264
SO_REUSEADDR 265
IP_TOS Class of Service 265
Socket Exceptions 267
Sockets in GUI Applications 268
Whois 269
A Network Client Library 272
9. Sockets for Servers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
Using ServerSockets 283
Serving Binary Data 288
Multithreaded Servers 289
Writing to Servers with Sockets 293
Closing Server Sockets 295
Logging 297
What to Log 297
How to Log 298
Constructing Server Sockets 302
Constructing Without Binding 304
Getting Information About a Server Socket 305
Socket Options 306
SO_TIMEOUT 307
SO_REUSEADDR 308
SO_RCVBUF 308
Class of Service 309
HTTP Servers 309
A Single-File Server 310
A Redirector 314
A Full-Fledged HTTP Server 319
10. Secure Sockets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
Secure Communications 326
Creating Secure Client Sockets 328
Choosing the Cipher Suites 332
Event Handlers 336
Session Management 336
Client Mode 338
Creating Secure Server Sockets 339
Table of Contents | ix
Configuring SSLServerSockets 343
Choosing the Cipher Suites 343
Session Management 344
Client Mode 344
11. Nonblocking I/O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
An Example Client 349
An Example Server 353
Buffers 359
Creating Buffers 361
Filling and Draining 363
Bulk Methods 364
Data Conversion 365
View Buffers 368
Compacting Buffers 370
Duplicating Buffers 372
Slicing Buffers 376
Marking and Resetting 377
Object Methods 377
Channels 378
SocketChannel 378
ServerSocketChannel 381
The Channels Class 383
Asynchronous Channels (Java 7) 384
Socket Options (Java 7) 386
Readiness Selection 388
The Selector Class 388
The SelectionKey Class 390
12. UDP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
The UDP Protocol 393
UDP Clients 395
UDP Servers 397
The DatagramPacket Class 399
The Constructors 401
The get Methods 403
The setter Methods 406
The DatagramSocket Class 408
The Constructors 409
Sending and Receiving Datagrams 411
Managing Connections 416
Socket Options 417
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
13. IP Multicast. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
Multicasting 444
Multicast Addresses and Groups 447
Clients and Servers 450
Routers and Routing 452
Working with Multicast Sockets 453
The Constructors 454
Communicating with a Multicast Group 455
Two Simple Examples 460
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
Table of Contents | xi
Java Network Programming Fourth Edition Harold Elliotte
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:
• Browsing the Web with HTTP
• Writing multithreaded servers
• Encrypting communications for confidentiality, authentication, and guaranteed
message integrity
• Designing GUI clients for network services
• Posting data to server-side programs
• Looking up hosts using DNS
• Downloading files with anonymous FTP
• Connecting sockets for low-level network communication
• Multicasting to all hosts on the network
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.
About the Fourth Edition
In 1996, in the first edition of this book’s opening chapter, I wrote extensively about the
sort of dynamic, distributed network applications I thought Java would make possible.
One of the most exciting parts of writing subsequent editions has been seeing virtually
all of the applications I foretold come to pass. Programmers are using Java to query
database servers, monitor web pages, control telescopes, manage multiplayer games,
and more, all by using Java’s native ability to access the Internet. Java in general and
network programming in Java in particular has moved well beyond the hype stage and
into the realm of real, working applications.
This book has come a long way, too. The fourth edition focuses even more heavily on
HTTP and REST. HTTP has gone from being one of many network protocols to almost
the network protocol. As you’ll see, it is often the protocol on which other protocols are
built, forming its own layer in the network stack.
There have been lots of other small changes and updates throughout the java.net and
supporting packages in Java 6, 7, and 8, and these are covered here as well. New classes
addressed in this edition include CookieManager, CookiePolicy, CookieStore,
HttpCookie, SwingWorker, Executor, ExecutorService, AsynchronousSocketChan
nel, AsynchronousServerSocketChannel, and more. Many other methods have been
added to existing classes in the last three releases of Java, and these are discussed in the
relevant chapters. I’ve also rewritten large parts of the book to reflect the ever-changing
fashions in Java programming in general and network programming in particular. I
hope you’ll find this fourth edition an even stronger, longer-lived, more accurate, and
more enjoyable tutorial and reference to network programming in Java than the pre‐
vious one.
Organization of the Book
Chapter1,Basic Network Concepts,explainsindetailwhataprogrammerneedstoknow
about how the networks and the Internet work. It covers the protocols that underlie the
Internet, such as TCP/IP and UDP/IP.
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.
ExperiencedJavaprogrammersmaybeabletoskimorskipthesetwochapters.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‐
loadinginformationandfilesfromnetworkserversofmanykinds.TheURLclassenables
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.
Who You Are
This book assumes you are comfortable with the Java language and programming en‐
vironment, in addition to object-oriented programming in general. This book does not
attempt to be a basic language tutorial. You should be thoroughly familiar with the
syntaxofJava.Youshouldhavewrittensimpleapplications.Italsowouldn’thurtifyou’re
familiar with basic Swing programming, though that’s not required aside from a few
examples. When you encounter a topic that requires a deeper understanding for net‐
work programming than is customary—for instance, threads and streams—I’ll cover
that topic as well, at least briefly.
However, this book doesn’t assume that you have prior experience with network pro‐
gramming. You should find it a complete introduction to networking concepts and
network application development. I don’t assume that you have a few thousand net‐
working acronyms (TCP, UDP, SMTP, etc.) at the tip of your tongue. You’ll learn what
you need to know about these here.
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.
About the Examples
Most methods and classes described in this book are illustrated with at least one com‐
plete working program, simple though it may be. In my experience, a complete working
program is essential to showing the proper use of a method. Without a program, it is
too easy to drop into jargon or to gloss over points about which the author may be
unclear in his own mind. The Java API documentation itself often suffers from exces‐
sively terse descriptions of the method calls. In this book, I have tried to err on the side
of providing too much explication rather than too little. If a point is obvious to you, feel
free to skip over it. You do not need to type in and run every example in this book; but
if a particular method does give you trouble, you should have at least one working
example.
Each chapter includes at least one (and often several) more complex programs that
demonstrate the classes and methods of that chapter in a more realistic setting. These
often rely on Java features not discussed in this book. Indeed, in many of the programs,
the networking components are only a small fraction of the source code and often the
least difficult parts. Nonetheless, none of these programs could be written as easily in
languages that didn’t give networking the central position it occupies in Java. The ap‐
parent simplicity of the networked sections of the code reflects the extent to which
networking has been made a core feature of Java, and not any triviality of the program
itself. All example programs presented in this book are available online, often with
corrections and additions. You can download the source code from http://www.cafeau
lait.org/books/jnp4/.
I have tested all the examples on Linux and many on Windows and Mac OS X. Most of
the examples given here should work on other platforms and with other compilers and
virtual machines that support Java 5 or later. The most common reasons an example
may not compile with Java 5 or 6 are try-with-resources and multicatch. These examples
can easily be rewritten to support earlier Java versions at the cost of increased verbosity.
I do feel a little guilty about a couple of compromises necessitated by the needs of space
in a printed book. First, I rarely check preconditions. Most methods assume they are
passed good data, and dispense with null checks and similar principles of good code
hygiene. Furthermore, I have reduced the indentation to two characters per block and
four characters per continuation line, as opposed to the Java standard of four and eight,
respectively. I hope these flaws will not be too distracting. On the positive side, these
compromises have aided me in making this edition considerably shorter (by several
hundred pages) than the previous edition.
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:
• Code examples and fragments
• Anything that might appear in a Java program, including keywords, operators, data
types, method names, variable names, class names, and interface names
• Program output
• Tags that might appear in an HTML document
A bold monospaced font is used for:
• Command lines and options that should be typed verbatim on the screen
An italicized font is used for:
• New terms where they are defined
• Pathnames, filenames, and program names (however, if the program name is also
the name of a Java class, it is given in a monospaced font, like other class names)
• Host and domain names (www.hpmor.com)
• URLs (http://www.cafeaulait.org/slides/)
• Titles of other books (Java I/O)
Indicates a tip, suggestion, or general note.
Indicates a warning or caution.
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!).
Request for Comments
I enjoy hearing from readers, whether with general comments about this book, specific
corrections, other topics they would like to see covered, or just war stories about their
own network programming travails. You can reach me by sending an email to
elharo@ibiblio.org.Pleaserealize,however,thatIreceiveseveralhundredpiecesofemail
a day and cannot personally respond to each one. For the best chance of getting a per‐
sonal response, please identify yourself as a reader of this book. If you have a question
about a particular program that isn’t working as you expect, try to reduce it to the
simplest case that reproduces the bug, preferably a single class, and paste the text of the
entire program into the body of your email. Unsolicited attachments will be deleted
unopened. And please, please send the message from the account you want me to reply
to and make sure that your Reply-to address is properly set! There’s nothing quite so
frustrating as spending an hour or more carefully researching the answer to an inter‐
esting question and composing a detailed response, only to have it bounce because my
correspondentsentherfeedbackfromapublicterminalandneglectedtosetthebrowser
preferences to include her actual email address.
I also adhere to the old saying “If you like this book, tell your friends. If you don’t like
it, tell me.” I’m especially interested in hearing about mistakes. This is the fourth edition.
I’ve yet to make it perfect, but I keep trying. As hard as I and the editors at O’Reilly
Preface | xix
workedonthisbook,I’msuretherearemistakesandtypographicalerrorsthatwemissed
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.
Using Code Examples
This book is here to help you get your job done. In general, if this book includes code
examples, you may use the code in this book in your programs and documentation. You
do not need to contact us for permission unless you’re reproducing a significant portion
of the code. For example, writing a program that uses several chunks of code from this
book does not require permission. Selling or distributing a CD-ROM of examples from
O’Reilly books does require permission. Answering a question by citing this book and
quoting example code does not require permission. Incorporating a significant amount
of example code from this book into your product’s documentation does require per‐
mission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author,publisher,andISBN.Forexample:“JavaNetworkProgramming,FourthEdition,
by Elliotte Rusty Harold (O’Reilly). Copyright 2014 Elliotte Rusty Harold,
978-1-449-35767-2.”
If you feel your use of code examples falls outside fair use or the permission given here,
feel free to contact us at permissions@oreilly.com.
Safari® Books Online
Safari Books Online is an on-demand digital library that delivers
expert content in both book and video form from the world’s lead‐
ing authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, government agencies, and individuals. Subscribers have access to thousands of
books, training videos, and prepublication manuscripts in one fully searchable database
from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐
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:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
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,
gotthingsrolling,andprovidedmanyhelpfulcommentsalongthewaythatsubstantially
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
socketsandcaughtallpossibleexceptions,andingeneralwrotethecleanest,safest,most
exemplary code I could write. John Zukowski found numerous errors of omission, all
nowfilledthankstohim.Andtheeagle-eyedAvnerGelbdisplayedanastonishingability
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
Network programming is no longer the province of a few specialists. It has become a
core part of every developer’s toolbox. Today, more programs are network aware than
aren’t. Besides classic applications like email, web browsers, and remote login, most
major applications have some level of networking built in. For example:
• 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.Topicscoveredinthischapterincludethenatureofnetworks;theTCP/IPlayer
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
2 | Chapter 1: Basic Network Concepts
match any primitive numeric data type in Java. The more bytes there are in each address,
the more addresses there are available and the more devices that can be connected to
the network simultaneously.
Addresses are assigned differently on different kinds of networks. Ethernet addresses
are attached to the physical Ethernet hardware. Manufacturers of Ethernet hardware
use preassigned manufacturer codes to make sure there are no conflicts between the
addresses in their hardware and the addresses of other manufacturers’ hardware. Each
manufacturer is responsible for making sure it doesn’t ship two Ethernet cards with the
same address. Internet addresses are normally assigned to a computer by the organi‐
zation that is responsible for it. However, the addresses that an organization is allowed
to choose for its computers are assigned by the organization’s Internet service provider
(ISP). ISPs get their IP addresses from one of four regional Internet registries (the reg‐
istry for North America is ARIN, the American Registry for Internet Numbers), which
are in turn assigned IP addresses by the Internet Corporation for Assigned Names and
Numbers (ICANN).
On some kinds of networks, nodes also have text names that help human beings identify
them such as “www.elharo.com” or “Beth Harold’s Computer.” At a set moment in time,
aparticularnamenormallyreferstoexactlyoneaddress.However,namesarenotlocked
to addresses. Names can change while addresses stay the same; likewise, addresses can
change while the names stay the same. One address can have several names and one
name can refer to several different addresses.
All modern computer networks are packet-switched networks: data traveling on the
network is broken into chunks called packets and each packet is handled separately.
Each packet contains information about who sent it and where it’s going. The most
importantadvantageofbreakingdataintoindividuallyaddressedpacketsisthatpackets
from many ongoing exchanges can travel on one wire, which makes it much cheaper to
build a network: many computers can share the same wire without interfering. (In
contrast,whenyoumakealocaltelephonecallwithinthesameexchangeonatraditional
phone line, you have essentially reserved a wire from your phone to the phone of the
person you’re calling. When all the wires are in use, as sometimes happens during a
major emergency or holiday, not everyone who picks up a phone will get a dial tone. If
you stay on the line, you’ll eventually get a dial tone when a line becomes free. In some
countries with worse phone service than the United States, it’s not uncommon to have
to wait half an hour or more for a dial tone.) Another advantage of packets is that
checksums can be used to detect whether a packet was damaged in transit.
We’re still missing one important piece: some notion of what computers need to say to
pass data back and forth. A protocol is a precise set of rules defining how computers
communicate: the format of addresses, how data is split into packets, and so on. There
are many different protocols defining different aspects of network communication. For
example, the Hypertext Transfer Protocol (HTTP) defines how web browsers and
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.
The Layers of a Network
Sending data across a network is a complex operation that must be carefully tuned to
the physical characteristics of the network as well as the logical character of the data
being sent. Software that sends data across a network must understand how to avoid
collisions between packets, convert digital data to analog signals, detect and correct
errors, route packets from one host to another, and more. The process is further com‐
plicated when the requirement to support multiple operating systems and heterogene‐
ous network cabling is added.
To hide most of this complexity from the application developer and end user, the dif‐
ferent aspects of network communication are separated into multiple layers. Each layer
represents a different level of abstraction between the physical hardware (i.e., the wires
and electricity) and the information being transmitted. In theory, each layer only talks
to the layers immediately above and immediately below it. Separating the network into
layers lets you modify or even replace the software in one layer without affecting the
others, as long as the interfaces between the layers stay the same.
Figure 1-1 shows a stack of possible protocols that may exist in your network. While
the middle layer protocols are fairly consistent across most of the Internet today, the
top and the bottom vary a lot. Some hosts use Ethernet; some use WiFi; some use PPP;
some use something else. Similarly, what’s on the top of the stack will depend completely
on which programs a host is running. The key is that from the top of the stack, it doesn’t
really matter what’s on the bottom and vice versa. The layer model decouples the ap‐
plication protocols (the main subject of this book) from the physics of the network
hardware and the topology of the network connections.
4 | Chapter 1: Basic Network Concepts
Figure 1-1. Protocols in different layers of a network
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.
Figure 1-2. The layers of a network
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‐
The Layers of a Network | 5
Random documents with unrelated
content Scribd suggests to you:
This transportation embraced the so-called "grub" and the
conveniences of a covered wagon in which one might ride on easy
roads, the expectation being that the passenger would walk up the
hills or over difficult tracts.
The captain of the outfit, a big, burly freighter, seemed proud to
have come from Pike County, Missouri, which he stated had
produced the most distinguished men whom he had ever known.
It had not been my privilege to meet any of the passengers
booked for this Missouri outfit until their arrival at the corral at the
appointed hour for starting. In accordance with the custom of the
country, each passenger was to furnish his own lodging; in other
words, each brought such blankets as were supposed to be
necessary for protection at night. My bundle was deposited in the
rear wagon, as I was desirous of securing the advantage of an
observation car, which would afford an unobstructed view behind us.
All the vehicles were ordinary large wagons with canvas covers.
THROUGH THE WASATCH
My companions in that wagon were two young men from Ohio,
each of whom had recently purchased a broncho horse, which he
intended to take back to the States and incidentally to use under the
saddle, as he might have opportunity, on the Eastward journey.
These two quadrupeds were haltered to the rear of the last wagon,
which they were expected to follow. That the bronchos might
become gradually accustomed to a burden upon their backs, the
young men had cinched tightly upon them their bundles of blankets.
Thus equipped we rolled out from the city up the terraced slope of
"the bench" toward the entrance into Parley's Canyon. (It may be
stated that the bench is the narrow level table land, evidently an
ancient shore line, that skirts the foothills of those mountains and
indicates that during some period the waters in the valley reached
that high level).
The young men had commented favorably on the docility of their
bronchos, which had for a time followed the wagon in a satisfactory
manner, and expressed the belief that the animals would afford
great comfort on the long trip, by enabling them to take horse-back
rides.
On entering an area covered with sage brush, a new purpose
seemed suddenly to enter the heads of the uncertain bronchos. It
may have been inspired by the sight of a little patch of grass on the
otherwise arid bench, or it may have been an innate inclination to do
something unexpected, an inclination very characteristic of the
broncho. Suddenly and almost simultaneously they dropped back on
their halters and were soon free and making a flight for the brush.
The young men watched their next proceedings with dismay. Having
reached an eligible location in an open space, the bronchos at once
began a series of evolutions so interesting that the train was brought
to a halt. In his favorite pastime of bucking, the broncho has no peer
among all the quadrupeds of the earth. It had been my privilege and
misfortune to make a personal test of this form of amusement and
with the usual results, but never before had I seen it so successfully
performed upon inanimate matter, as on this occasion in the sage
brush of Utah.
The bundles upon the bronchos were light, and were strapped
tightly upon them with double girths. The buckers operating closely
together apparently entered into a contest, to ascertain which of the
two could first relieve himself of his impedimenta.
While the train was at rest, the boarders and drivers secured
favorable positions, where they might witness the match. Our
captain from Pike County, Missouri, broke forth into curses, berating
the intelligence of any man who would buy such good-for-nothing
creatures, and yet he was the first person to assist in their capture.
Again and again the bucking bronchos, facing each other, repeated
their vicious plunges, leaping into the air with heads down and backs
curved upward, and coming down upon their fore feet, until in some
way the bundles were dashed upon the ground and their contents
were widely distributed under the animals' feet, after which a sense
of victory and freedom seemed to come over them, and only after a
long pursuit were they again secured. During the time that I
remained with the train, no human being ventured to mount the
refractory brutes.
The night came on as we turned into camp near the summit of
the canyon. The familiar fragrance of fried bacon and coffee was
beginning to pervade the atmosphere when the captain from Pike
County gave the command to "fall to," which was his method of
announcing to the boarders that supper was served. Drawing around
the camp fire we faced the same old "Menu" and the same type of
battered tin dishes and cutlery that we had become familiar with on
our own train, except that the cooking and serving paraphernalia
bore evidences of greater antiquity and more violent service.
We sat or kneeled upon the ground in a sort of irregular semi-
circle. With but few exceptions each man was a stranger to all the
others. Each man had a revolver in his belt, and in most cases the
men had rifles with their effects in the wagons. Each was curious to
know where the other fellow came from, and without much
ceremony the blunt, but good-natured question, "Where do you hail
from?" was propounded to one's neighbor in the circle. The roster
was soon completed, and before we left the camp fire my record
showed that one of the party had recently closed his apprenticeship
under Morgan, the raider; another, an ex-confederate, was from Old
Virginia; one was from the Sandwich Islands; one from New
Hampshire; one each from Arkansas, South Carolina, Michigan, and
Wisconsin, and two were from Missouri. Our cook was a young
Snake Indian, but the rest of the crew had not yet disclosed any
facts concerning their life-history.
From the members of such a miscellaneous gathering there
came naturally some sparring and good-natured reviling tinged at
times with acrimony, for the bitterness of the Civil War had not yet
materially lessened. But after the first parry of words all realized that
they were now comrades for mutual protection.
A quiet place was soon found up the mountain side, and
wrapping my blanket around me I watched the bright stars until I
fell asleep.
In the morning we had a touch of camp life that was calculated
to bring to the surface that trait of character which would manifest
itself in an hour of trial. The captain had been heard to shout from a
distant point, where he was attending to a mule, to ask the young
Indian cook why in h—l he didn't call breakfast, as it was time for
the train to pull out. The brush fire had burned long enough to have
boiled coffee many times, but the Snake Indian seemed to be
wandering abstractedly round the wagons as if searching for some
missing article. As the Captain approached and again demanded an
explanation for the delay, the boy informed him, in the few English
words at his command, that some one had taken the bacon. He
declared that the great slab of meat referred to had on the night
before been placed in the covered mess box at the tail end of the
wagon.
The Captain again swore, and, with the air of a commander of
men, proceeded in his endeavors to solve the mystery. Two mules
had been picketed all night near the wagon, and the Captain,
doubtless aware of the omnivorous habits of those amalgamated
beasts, examined their surroundings, and observed squarely under
the fore feet of one an elevated surface that appeared suspicious.
He backed the mule, and with his foot scraped away an inch or two
of dirt, beneath which he struck the stratum of bacon, disfigured
somewhat by the heavy pressure of the animal's hoofs, but
nevertheless recognizable as bacon. The mule had evidently, at
some time during the night, lifted the lid of the mess box with his
nose, and seizing the bacon with his teeth had undertaken the task
of eating it, but finding some coarser food better suited to his
incisors had abandoned the bacon in disgust, dropped it upon the
ground, pawed dirt upon it, and then planted his feet on the pile.
"Here's your bacon," said the Captain, with an oath, and a sneer
of superiority. "Now hurry up that breakfast." This event occurred
prior to the development of our present theory of germs and the
sterilization of food, so vexing to modern epicures.
An empty stomach needs no appetizing sauce. When I have
listened to adverse criticisms concerning dishes served at elaborately
prepared banquets, I have more than once recalled that breakfast of
bacon and coffee prepared by a Snake Indian cook in the Wasatch
Mountains. There was no bacon to be wasted.
On those clear frosty nights it was a pleasure to creep up the
mountain side, and beneath the open starry sky to roll up in a
blanket and be lulled to sleep by the music of streams rushing down
those canyons. Strange as it may seem, no colds ever resulted from
this life in the open air. Every breath inhaled in the waking hours or
while asleep, was of pure air not vitiated by exhalations from the
lungs of others, nor breathed in part over and over again. This
immunity from colds is also true under some conditions that might
seem seriously dangerous to one accustomed only to the comforts of
civilized life. An example of this was afforded on Tuesday evening,
the 18th of September, when we reached Quaking Asp Hill, near the
summit of the Divide. A fine driving rain, which extinguished our
fires, began to fall at dusk, before we had finished our bacon and
coffee, and there were indications of a cold and heavy storm. That
he might the better protect himself against the elements, the
Sandwich Islander entered into negotiations to double our blankets,
a proposal that was promptly accepted, as he was provided with one
which was waterproof to place on the wet ground. Each of us had
the regular double army blanket and overcoat. This was not the first
rainy night that I had spent without a roof above me, but it was
certainly the wildest.
As the night advanced and the wind was blowing violently, we
naturally turned our feet toward the gale and loaded the edges of
the blankets with rocks to hold them in place. We then settled down
to await the time when the water would penetrate our clothing.
Fortunately the rain turned into a driving snow storm. The gale
veered round and came from the North, increasing in intensity, and
although our blankets were frozen, the wind now coming toward our
heads, pressed down between us and lifted the covering like a
balloon until it found escape at our feet, while the covers waved and
flapped in the air. It seemed too late to reverse our position, but we
held tightly to the coverings until the accumulating snow gradually
weighted them down. The wind also became more moderate toward
midnight, but the snow continued to fall rapidly until after we fell
asleep. My companion and I had "spooned" as closely as possible
that we might share each other's warmth, and if one was inclined to
turn over his partner promptly responded.
I awoke after daylight, conscious of the heavy weight resting
upon us. Opening my eyes I looked upward through the white funnel
in the snow which had been formed by our breaths, melting the
falling flakes, but everything was still. The storm had ceased, and
although the sun had not yet risen above the mountain peaks, we
saw that a bright morning was dawning upon us. A council with my
companion led us to lift the blankets with care, and remove the
weight of snow that covered us. After rising to a sitting position, it
was discovered that we were not alone. Here and there at different
points were undulations on the brilliant white surface of the snow. In
one end of each of these was the funnel which told us that the warm
breath of the sleepers had also preserved for them an open view of
the sky above.
Must we, as first-class boarders, dig the walks through the snow
and build the fire? We decided in the negative, and accordingly
called the camp to service. One by one snow mounds were lifted and
living beings arose from beneath the thick white mantle. The Captain
had slept in his wagon, but he promptly assumed command.
Preparations were soon under way for breakfast, and the stock was
cared for. Nearly eight inches of snow had fallen. Not a track was
visible to guide us along the road during the greater part of the
following day, but as we descended into the valleys, there was but
little snow upon the ground, and that disappeared rapidly. Not one
of our party "caught cold."
The days rolled by until one morning after we had passed Fort
Bridger, we met our long ox train moving Westward. It halted until I
could transfer my baggage, after which I bade a hearty farewell to
the fellow travelers in the boarding-house train. Taking possession of
a good saddle horse, I started Westward again with our own long
caravan.
This brings us to new experiences. It was no trifling matter to
conduct a long ox train up and down the mountain canyons, as will
be discovered later. This was not because it was difficult to find the
trail, but it was because the trail itself was often difficult. It was the
principal highway through the ranges of mountains, and from Fort
Bridger westward was the regular stage road, yet it was often steep
and dangerous. Captain Whitmore and his men were somewhat
weary, having had a hard trip, and my services, therefore, seemed to
be very welcome. The provisions were running low. Sugar for coffee
and soda for bread were long since exhausted. In fact, the stock of
food was reduced to flour, bacon, and a little coffee. Milk or
vegetables were never obtainable, and canned goods had not come
into use. Two or three men who were with the train had endeavored
to incite the others to rebellion, and appearing before Captain
Whitmore told him substantially in the words once addressed to
Moses of the time when back in the States, "They sat by the flesh
pots and did eat bread to the full," but now they could not get a
square meal in the wilderness. It appears that these mutineers were
recognized by their companions as wasteful, shiftless men, too
proud and lazy to work when at home. From Whitmore's rulings
there would be no appeal in that country, except to the law of force.
There were no cucumbers, melons, leeks, or onions in that
wilderness. Bacon or unleavened bread or death was the alternative,
unless they could hustle for wild game. Regarding the subsequent
careers of the three men above referred to as an object lesson, it
may be interesting to note the fact that to the end of their lives none
appeared ever to be in a position to assist another, or to keep want
from his own door.
It was along this road that we fell in with Captain Chipman's ill-
starred train of Mormon emigrants. Mingling with the Pilgrims in
their camp, I became interested in a young Englishman named S. W.
Sears, whose history is full of adventures and chequered with varied
experiences.
Although then but twenty-two years of age, he was chaplain of
the train; for be it known that notwithstanding the sins ascribed to
the Mormons, they maintained regular devotional services in camp
as well as temple. Sears' wife had died on their westward pilgrimage
six months after their marriage and was buried on the banks of the
North Platte.
A few days later their train was attacked by Indians who
captured 300 of their horses and oxen.
The emigrants saved enough of their stock to move their wagons
in divisions until they escaped from the hostile Indian territory.
Sears became prominent both as a missionary of the Mormon
faith and in commercial life. Two wives survived him, one of whom
was the adopted daughter of the distinguished Daniel H. Wells and
was born in a wagon near the entrance to the city at the termination
of her mother's long journey across the plains.
Travel, like politics, makes strange bedfellows, and especially
that kind of travel in which all companions must, from necessity,
mingle on a common level, eat their simple rations by the same
camp fire, and sleep side by side beneath the same open sky. This
observation is suggested by a night spent in camp near Bear River.
Our ox train had just forded that rocky stream, to avoid the
excessive toll which was demanded for the privilege of crossing upon
the new bridge. Before going into camp near by, the Captain of a
little train that had preceded us rode his horse rapidly into the
stream in his effort to head off some intractable mules. The horse
stumbled over some stones and fell upon its knees, throwing the
rider over his head in a fairly executed somersault into the water.
The feat evoked hearty applause from those who were fortunate
enough to witness it.
Now it happened that among the men with our train was a
modest but vigorous young man named Ferdinand Lee, whom I had
known quite well before he had served his full time during the war
just ended as a private in the Second Wisconsin Regiment, which
distinguished itself as part of the famous Iron Brigade.
After supper I walked up the bank of the stream with Ferd,
which was the name by which Lee was familiarly known, and we
soon encountered a group of men composed of stragglers from two
small parties that were camping near by and who like ourselves had
gravitated toward the best camp fire.
"Was it your Captain what made that h—l of a dive from his hoss
into the river?" asked a tall, black-whiskered Southerner of a small,
red-headed chap, who we learned later was known as Sandy.
"I reckon it war. Didn't he do it all right?" was the reply. "What's
your name, anyhow?" he continued.
"Well, it don't make much difference, but these fellows call me
Shorty, and I was wondering if that Captain ever rid a hoss before."
"Guess he has, because he says he was in the army and raided
in Kentucky with the Rebs," replied Sandy. "Those Kentuckyans think
they can ride, you know." And with this he took a seat upon a little
rock, lighted a pipe, and others followed his example.
"I guess you're a Yank," said Shorty.
"Well, I reckon I am," said Sandy, "and while we are guessing I
would put you down for a Johnny Reb." A frown came over Shorty's
face, when he said, with some bitterness, "You think the Kentucky
boys can't ride much, hey?"
"I recollect hearing them tell about your General Winne, when
he and some of his boys here were pretty close together near the
Wilderness Tavern. He did the same thing in the water of Flat Run
that your Captain did in Bear River."
"War you in the Wilderness two years ago?" asked Sandy.
"I was in the Iron Brigade of Maryland, sir."
"Then I reckon you have seen General Winne. But don't you
think you fellows did a lot of careless shooting around there?"
"Wa'al, we pumped some lead the best we knew how, but were
you careless enough to be standing around in that country when
shooting was going on?" asked Shorty.
"There's a bullet inside of me that once in a while tells me that
mebbe I wasn't in jest the right place."
"What company were you in?" asked Shorty.
"I was fooling around a little with the Twentieth Maine," was the
reply.
Ferd Lee had been a quiet but interested listener. One of our
boys, without turning his head remarked that Lee just behind him
did some business in the Wilderness.
"Lee? That's a good Virginia name. But you were not in our
Brigade, were you?"
"No," replied Ferd. "I loafed around a few years with the Second
Wisconsin in the Iron Brigade."
Shorty instantly rose to his feet, and approaching Ferd said, "I
have surely met you before, sir. Although I hate the Yankees, I
respect the bravery of the men in your Brigade, and I want to shake
your hand."
Ferd rose, took the hand of the Confederate veteran, and they
looked into each other's eyes as the firelight flickered in their faces,
when Ferd said, "No men ever fought better than yours did."
The Iron Brigade had earned its name through the valor and
inflexible courage of its men on many battle-fields, and its Second
Wisconsin Regiment had borne an honorable part in its achievement.
Thus, for the first time since they had met in conflict on the
battle-fields of Virginia, those veterans again confronted each other.
True, the war was over, but it had left its bitterness. Nevertheless,
like other brave men, they were impelled to respect the soldiers on
the opposing side, whose deeds had been as valorous as those of
any heroes immortalized in poetry and song. Until late that night, by
the peaceful camp fire on the banks of Bear River, the boys
rehearsed the thrilling events in which they had participated in the
effort to shed each other's blood.
As would naturally be supposed, Captain Whitmore, as the
opportunity presented itself, gave me from time to time the story of
his experience thus far during his trip. One event, the particulars of
which were confirmed by his men, seemed to be so interesting that I
asked him to describe it again to another party of travelers at our
night's camp. It appears that one afternoon his ox train was slowly
crawling along near the north slope of a low range of hills west of
Julesburg. A family of emigrants from Illinois consisting of a man, his
wife, a grown son and a daughter about eighteen years of age, and
a couple of assistants, had accompanied the train from the last
military post. As these emigrants had horse teams, which travel
somewhat faster than oxen, they were accustomed to driving half a
mile or more in advance of the big train, although they had been
warned of the hazard; but there they were on that fatal day to
receive unaided the brutal raid of a band of Indians which swooped
down from the hills. John Wilson on horseback and Mr. Stone of
Iowa on foot were out in opposite directions for a hunt.
Simultaneously with the attack on the emigrant's wagons, Wilson
was seen racing down a valley toward the train pushing his horse to
the top of its speed, and in close pursuit was a band of mounted
savages yelling like demons. At the same moment Mr. Stone, who
was in full view not a mile distant, became the object of an attack
from still another detachment of warriors also on horse-back. The
train was corralled in a circle for defense as speedily as possible. In
the meantime Stone displayed marvelous tact and coolness. He was
armed with a Henry repeating rifle loaded with sixteen cartridges,
and, as was the usual custom with all hunters, he also carried in
addition a case of loaded cartridges. On discovering the rapid
approach of the savages he hastened to the top of a little mound
that was near by and dropped upon his face. Pursuing their usual
tactics the Indians in single file rode swiftly in a circle round and
round the apparently doomed Iowan, gradually approaching their
victim, who would soon be within range of their arrows. Stone
remained quiet for a few moments until his enemies, filing rapidly by
the line of his aim as they passed, were within fairly safe range, and
then his rifle, directed with careful precision, opened up a series of
discharges such as they probably had never before seen, for the
Henry was a newly invented weapon and the savages doubtless
intended to close in as soon as the rifle should be discharged. In
Stone's first series of shots he emptied three saddles of their riders
and wounded two horses. While the savages then swung outward
for a moment, time was given him to refill the chamber of his rifle
with fresh cartridges when at once he renewed his defensive tactics,
with results that were startling. The Indians who were still in action
seemed to be perplexed by the strange, persistent weapon that was
turned upon them, and slowly withdrew. Stone retreated toward the
train and was soon under cover of its rifles. The emigrant's party
fared badly. All were slaughtered except the young girl, who was
captured alive and was taken off with the horses and the plunder
from the wagons. I learned later that she remained in captivity until
the following spring, when she was restored to the military and
thence transported to her former home.
Wilson reached a point where his exhausted horse, which had
fully shared in the panic, fell prostrate to the ground and never again
rose to its feet. The train, now well fortified and defended, escaped
further loss.
It may be remembered, as was narrated in another chapter, that
in the early days of our expedition and away back in the little village
of Churchville, Iowa, a young girl disguised in boy's apparel
succeeded in joining the train and became an assistant to the man
and his wife who were the cooks for the outfit. After our little party
proceeded in advance of the big train from Nebraska City we
received no definite tidings concerning its progress until the meeting
near Bridger, which has just been described. It was therefore a great
surprise, on now again reaching the train, to learn that the girl had
thus far shared the hardships and perils of the entire journey. What
would lead a young, apparently modest, and prepossessing country
maid to embark on a long trip with a body of strangers destined to a
far away Mormon town in the mountains? Before being permitted to
proceed from Nebraska City, it appears that she gave out some
statements concerning her history. From these it transpired that she
was an orphan about nineteen years of age. She had a lover, who,
she confidently believed, was in Salt Lake valley. It seemed to be the
old story of a trustful, confiding girl and possibly a recreant wooer, in
whom she still had unbounded faith. She was intelligent for one of
her years and was apparently sincere and thoroughly in earnest.
"Yes, he is right there in the valley, and he does not know that I
am going to meet him," she said. But, young girl, there are
hundreds of canyons and branch canyons reaching out from the
valleys around Salt Lake basin. Many of them are seldom trodden.
Some, difficult of access, invite the adventurer to their remotest
nooks, where the fortune-hunter would seek for gold or silver. How
will you find him?
"Hope is a lover's staff," and on that frail support her future
rested. She had come to be known to the boys with the train, many
of whom had been soldiers, as the child of the regiment.
We well remember how she then appeared as she was about to
enter practically alone into the turbulent life of the little city of Salt
Lake, for it must be understood that the train men must there
separate, and while she might receive some assistance, she must
fight her own battles.
If any old resident of Churchville, Iowa, knew a bright,
handsome young girl of medium height with dark hair and big dark
eyes who in the spring of sixty-six suddenly disappeared from that
village he may get this little glimpse of her history. Her real name
was always withheld. The name by which she was known to our
boys would have no significance to her former acquaintances. I
never saw her again after the train reached the city. She suddenly
vanished in the whirlpool of western life.
It was reported that a young girl answering the description of
our whilom ward was one morning seen riding alone on horse-back
up City Creek canyon, to which valley hundreds of men had that
year been attracted by rumors of gold discoveries. And so must end
a tale half-told.
During those days I was assisting on horse-back in various ways,
and at times conducting the long train round the sharp curves in the
canyons. Six or eight yokes of oxen drawing two large wagons
coupled together is a long thing in itself, stretching out perhaps 150
feet. It may run beautifully on a straight road, but in rounding a
short bend in a narrow roadway, where the inside of the bend is on
the edge of a precipice, the tendency is to bring the wagons
dangerously near the brink.
On the third of October, our train was winding along the narrow
roadway among the cliffs of Silver Creek Canyon. Looking across a
deep ravine before us we observed the last wagon in the train that
was crawling along in advance of ours, to be encroaching on the
edge of a precipice, and in a moment a wheel slipped over the bank.
The great prairie schooner capsized, breaking the tongue, detaching
the wagon from the teams, and turned upside down. Down, down it
rolled, repeatedly bounding over rocks and through bushes, until it
found a resting place quite out of sight near the bottom of the
canyon. As we approached the scene of the catastrophe an odor,
recognized by experienced drivers as of whiskey, came from the
wreck of the wagon. We passed on as soon as the way could be
opened. A number of men from the delayed train seemed inspired
with a benevolent impulse that led them to assist in saving
something from the wreck, and were soon clambering down the
rocks toward the spot from which the fragrance came the strongest.
We learned nothing of the final results of the work of this
salvage corps. Their voices, which came up from the hidden depths,
indicated that they had found something, and the odors were
evidence that enough fire water had been spilled to have made a
whole tribe of the solemnest Indians hilarious.
On the afternoon of the same day, in going down a steep
descent in the same canyon, the failure to fasten the brake on one
of our wagons caused the two that were coupled together to gain so
much headway that they pressed the ox teams into a frightened
mass. The breaking of the wagon tongue turned the wagons down a
long steep slope leaving the road more than five hundred feet
above. We now had our own troubles. After taking a survey of our
wreck, which consisted of a load of miscellaneous merchandise and
a wagon in trail, on which was a heavy boiler, I rode back to the little
settlement of Wanship for articles needed in repairs.
In the meantime the train was corralled further down the
canyon, and the stock wandered up the mountain valleys.
In the morning many oxen were missing which it was my
pleasure to assist in finding, for I loved the hills. Mounting a horse, I
ascended a ravine and crossed two or three mountain spurs where it
was hoped a glimpse of the strays or their tracks might be obtained.
Looking from a concealed position across a deep valley, I
observed on the opposite slope an animal which I became satisfied
was a mountain sheep, the Big Horn. I had seen many specimens of
the various animals and birds indigenous to the West, but never a
mountain sheep, except in captivity. They are wary animals, and like
the chamois of the Alps are at home on the rocky cliffs. I must be
cautious. My horse was fastened behind me, out of view, down the
mountain slope. My Henry rifle was in good condition. Lying on my
face while carefully sighting through the underbrush, I felt myself to
be absolutely safe from discovery. Calculating the distance as
accurately as possible, a careful aim was taken, but the bullet fell far
short of the mark, striking the rocks away beneath. The animal was
evidently unconscious of my death-dealing purpose, and nestled
quietly half-concealed in a growth of underbrush. Another shot was
fired, when it became evident that my Henry was not of sufficiently
long range to reach the game. The opportunity before me was too
rare to be sacrificed without effort. Therefore, after tying a silk
handkerchief to a limb to mark the trail to my horse, I skirted the
spur of the mountain, on foot, slowly descended into the ravine, and
laboriously clambered up the other side.
The time and effort expended in accomplishing the ascent to the
other side made it clear that I had been greatly deceived in the
distance, but I was happy to make any physical effort to secure a
mountain sheep. The last quarter of a mile must be made with
exceeding caution, because the quick ear of the Big Horn would
catch any unusual sound. After more than an hour of vigorous but
cautious climbing, an eligible point was reached, toward which my
course had been directed, and with rifle ready to fire on the first
sight of the game, my head was slowly raised above a projecting
rock in confidence that the game had not ascended the mountain.
There it was in full view, not more than a hundred yards distant. It
certainly had horns, but the sight of half a dozen ordinary sheep
huddled together in the background revealed to my obtuse
consciousness the fact that my game was a ram, which was
guarding a little flock of domestic sheep similar to those with which
we are all familiar.
Shall victory be wrested from defeat? Our boys needed meat,
and I could tumble a sheep's carcass down the mountain side.
Conflicting emotions throbbed within my breast, until approaching
the sheep I was confronted by a tough-looking mountaineer, after
which I cared less for mutton.
"What are ye doin' up here?" was his interrogatory.
"Oh, I'm out a hunting."
"What kind of game are ye after?" he asked.
"Oh, any nice game that needs a good shot."
I noticed that the stranger had a revolver at his side, and in a
few moments another slouched-hat individual emerged from a little
hut in a side ravine.
"What kind of a rifle is that you've got?"
"It's a Henry."
"I've hear'n of one but never seen one before. Lemme see it,"
said the mountaineer. He took the gun from me and carefully looked
it over. "Where are you from, anyhow?" he asked, without taking his
eyes from the gun. I gave the name of the town without any
additional facts. Continuing, he said, "I was there once. I lived up in
Bark Woods awhile. Do you know where Pumpkin Holler is, just
beyond Hebron?"
"Yes."
"Did you ever know Jim Roach, who hauled logs to Joe Powers'
saw mill at Hebron?"
"The holler is several miles from my town, but I think I have
heard the name," I replied.
"Didn't you ever hear of Jim Roach's nephew Ben?" he asked.
"Maybe I have," was the answer.
"Well!" said the mountaineer, "I'm him."
Java Network Programming Fourth Edition Harold Elliotte
I
CHAPTER XXVIII
Some Episodes In Stock Hunting
N later years, through the influence of one of its ambitious
citizens, the little settlement referred to in the last chapter
as Pumpkin Holler had come to be known by the more
classic if less appropriate name of Rome. There was,
however, nothing in my recollection of that sleepy crossroads
or of its alleged former citizen, Benjamin Roach, and his friend, that
would tempt me to remain longer than necessary in their mountain
fastness, nor did I invoke their aid or inform them that a number of
our cattle had strayed up the adjacent valleys. It was the current
belief that some men who lived in those parts, having no other
visible means of support, were inclined to care for stray stock, and
pursued that avocation as a pastime chiefly in their own interest. As
soon, therefore, as the Henry rifle was again in my hands, I
retreated down the mountain side through the thickets of
underbrush and then up the other side of the valley. The silk
handkerchief, which had been left on the opposite cliff as a
landmark, served a good purpose as it enabled me to reach my
horse by a fairly direct course.
The lengthening shadows on the mountain slopes were a
warning that I should speedily proceed to the business of hunting
cattle. It was nearly sunset when I caught a glimpse of oxen nearly
a mile distant and partly concealed by a grove near which they were
grazing. Being confident that they were part of our missing stock I
started to reach them. The steep, rough, and rocky mountain slope
which was hurriedly descended in the quest was ill adapted to horse-
back riding and the pathless groves of underbrush proved to be
serious obstructions to progress. Becoming entangled in the
unyielding branches the stock of my rifle was broken squarely off,
and a few new holes in size beyond the skill of the novice to repair,
were punched through my garments in places where additional holes
were unnecessary. On emerging into an open space, it was found
that both horse and rider had received a few scratches, and the
bridle was broken. All these mishaps were ordinary incidents to
which any stock hunter is subject if he is inclined to wander
unnecessarily into new and untrodden paths, but the big whip, the
favorite artillery of the cowboy, was saved. Our wayward oxen were
finally rounded up far up a valley where the grass grows the
greenest, but with temper not unlike that of men they evidently
preferred the freedom of the mountains to a condition of servitude.
Apparently understanding my purpose they scattered in a wild race
to avoid, if possible, being again brought under the heavy yoke, but
were finally brought to the corral down the canyon.
Our troubles were not yet ended. On the following day two more
wagon wheels collapsed on a steep slope. The train was again
halted. The stock was turned out upon the range with its numerous
ramifications of ravines and thickets, and before the morning
dawned many of the animals were out of our sight.
We were not traveling on schedule time, yet this delay brought
forth some outbursts of profanity from those who were accustomed
to swear, all of which produced no effect on the cattle scattered up
the valleys. On the following morning there began another series of
experiences in hunting stock, which afforded a fair illustration of the
manner in which the Western Mountaineer of that day lived and tried
to sleep.
Taking a heavy horse, which unfortunately was not adapted to
mountain climbing, I started alone southward up a long side ravine
directed in part by the tracks of the oxen. Having reached rather a
high altitude, and desiring to obtain a better view of the surrounding
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
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.
Let us accompany you on the journey of exploring knowledge and
personal growth!
textbookfull.com

More Related Content

Similar to Java Network Programming Fourth Edition Harold Elliotte (20)

PDF
Download full ebook of Restfulnet 1st Edition Jon Flanders instant download pdf
roanematot2s
 
PDF
Programming Coldfusion Mx 2nd Edition Rob Brooksbilson
kurohaost
 
PDF
Javascript Web Applications Otx Alex Maccaw
fahradzereit93
 
PDF
Practical Modperl First Edition Bekman Stas Cholet Eric
toyahwaierys
 
PDF
Download ebooks file Practical mod_perl 1st Edition Stas Bekman all chapters
cevadkulah
 
PDF
Sdn Software Defined Networks 1st Edition Thomas Nadeau D Ken Gray
ninhhzhkal622
 
PDF
Tcpip Network Administration 3rd Edition 3rd Edition Craig Hunt
penzybilmar
 
PDF
Flask Web Development 1st Edition Miguel Grinberg
cjvsgfu2766
 
PDF
Programming Ios 4 Fundamentals Of Iphone Ipad And Ipod Touch Development 1st ...
jungieaugi
 
PDF
Practical mod_perl 1st Edition Stas Bekman
khuphejavadi
 
PDF
High Performance JavaScript Build Faster Web Application Interfaces 1st Editi...
yarecofuxxa58
 
PDF
SDN Software Defined Networks 1st Edition Thomas Nadeau D.
aneyaromiel8
 
PDF
Learning Web App Development 1st Edition Semmy Purewal
vhnnoomvci971
 
PDF
Web_Development_with_Node_Express.pdf
Marco Antonio Martinez Andrade
 
PDF
Even faster web sites 1st Edition Steve Souders
huapepotts09
 
PDF
AWS System Administration Best Practices for Sysadmins in the Amazon Cloud 1s...
pulbzlod930
 
PDF
Programming Windows Azure Programming the Microsoft Cloud 1st Edition Sriram ...
gjuzjatshuba
 
PDF
AWS System Administration Best Practices for Sysadmins in the Amazon Cloud 1s...
koidemoreaqb
 
PDF
C 40 In A Nutshell Fourth Edition Joseph Albahari Ben Albahari
nkokiveloce
 
PDF
Designing Evolvable Web Apis With Aspnet 1st Edition Glenn Block
zisanashham6
 
Download full ebook of Restfulnet 1st Edition Jon Flanders instant download pdf
roanematot2s
 
Programming Coldfusion Mx 2nd Edition Rob Brooksbilson
kurohaost
 
Javascript Web Applications Otx Alex Maccaw
fahradzereit93
 
Practical Modperl First Edition Bekman Stas Cholet Eric
toyahwaierys
 
Download ebooks file Practical mod_perl 1st Edition Stas Bekman all chapters
cevadkulah
 
Sdn Software Defined Networks 1st Edition Thomas Nadeau D Ken Gray
ninhhzhkal622
 
Tcpip Network Administration 3rd Edition 3rd Edition Craig Hunt
penzybilmar
 
Flask Web Development 1st Edition Miguel Grinberg
cjvsgfu2766
 
Programming Ios 4 Fundamentals Of Iphone Ipad And Ipod Touch Development 1st ...
jungieaugi
 
Practical mod_perl 1st Edition Stas Bekman
khuphejavadi
 
High Performance JavaScript Build Faster Web Application Interfaces 1st Editi...
yarecofuxxa58
 
SDN Software Defined Networks 1st Edition Thomas Nadeau D.
aneyaromiel8
 
Learning Web App Development 1st Edition Semmy Purewal
vhnnoomvci971
 
Web_Development_with_Node_Express.pdf
Marco Antonio Martinez Andrade
 
Even faster web sites 1st Edition Steve Souders
huapepotts09
 
AWS System Administration Best Practices for Sysadmins in the Amazon Cloud 1s...
pulbzlod930
 
Programming Windows Azure Programming the Microsoft Cloud 1st Edition Sriram ...
gjuzjatshuba
 
AWS System Administration Best Practices for Sysadmins in the Amazon Cloud 1s...
koidemoreaqb
 
C 40 In A Nutshell Fourth Edition Joseph Albahari Ben Albahari
nkokiveloce
 
Designing Evolvable Web Apis With Aspnet 1st Edition Glenn Block
zisanashham6
 

Recently uploaded (20)

PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Ad

Java Network Programming Fourth Edition Harold Elliotte

  • 1. Java Network Programming Fourth Edition Harold Elliotte pdf download https://textbookfull.com/product/java-network-programming-fourth- edition-harold-elliotte/ Download more ebook from https://textbookfull.com
  • 2. We believe these products will be a great fit for you. Click the link to download now, or visit textbookfull.com to discover even more! Learning Network Programming with Java 1st Edition Reese Richard M https://textbookfull.com/product/learning-network-programming- with-java-1st-edition-reese-richard-m/ Neural Network Programming with Java Create and unleash the power of neural networks by implementing professional Java code 1st Edition Souza https://textbookfull.com/product/neural-network-programming-with- java-create-and-unleash-the-power-of-neural-networks-by- implementing-professional-java-code-1st-edition-souza/ Java Programming Joyce Farrell https://textbookfull.com/product/java-programming-joyce-farrell/ Java Programming Joyce Farrell https://textbookfull.com/product/java-programming-joyce- farrell-2/
  • 3. Java pocket guide Fourth Edition Robert Liguori https://textbookfull.com/product/java-pocket-guide-fourth- edition-robert-liguori/ Programming in Java Sachin Malhotra https://textbookfull.com/product/programming-in-java-sachin- malhotra/ Python Network Programming Cookbook Kathiravelu https://textbookfull.com/product/python-network-programming- cookbook-kathiravelu/ CompTIA Network Review Guide Fourth Edition. Edition Craig Zacker https://textbookfull.com/product/comptia-network-review-guide- fourth-edition-edition-craig-zacker/ Learning Java Beginning programming with java for dummies First Edition John Bach https://textbookfull.com/product/learning-java-beginning- programming-with-java-for-dummies-first-edition-john-bach/
  • 6. Elliotte Rusty Harold FOURTH EDITION Java Network Programming
  • 7. Java Network Programming, Fourth Edition by Elliotte Rusty Harold Copyright © 2014 Elliotte Rusty Harold. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are alsoavailableformosttitles(http://my.safaribooksonline.com).Formoreinformation,contactourcorporate/ institutional sales department: 800-998-9938 or [email protected]. Editor: Meghan Blanchette Production Editor: Nicole Shelby Copyeditor: Kim Cofer Proofreader: Jasmine Kwityn Indexer: Judy McConville Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest October 2013: Fourth Edition Revision History for the Fourth Edition: 2013-09-23: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449357672 for release details. 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]
  • 8. This book is dedicated to my dog, Thor.
  • 10. Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Basic Network Concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Networks 2 The Layers of a Network 4 The Host-to-Network Layer 7 The Internet Layer 8 The Transport Layer 9 The Application Layer 10 IP, TCP, and UDP 10 IP Addresses and Domain Names 11 Ports 13 The Internet 14 Internet Address Blocks 15 Network Address Translation 15 Firewalls 15 Proxy Servers 16 The Client/Server Model 18 Internet Standards 19 IETF RFCs 20 W3C Recommendations 22 2. Streams. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Output Streams 26 Input Streams 31 Marking and Resetting 34 Filter Streams 35 Chaining Filters Together 37 Buffered Streams 38 v
  • 11. 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
  • 12. Processing Web Server Logfiles 112 5. URLs and URIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 URIs 117 URLs 120 Relative URLs 122 The URL Class 123 Creating New URLs 123 Retrieving Data from a URL 128 Splitting a URL into Pieces 135 Equality and Comparison 139 Conversion 141 The URI Class 141 Constructing a URI 142 The Parts of the URI 144 Resolving Relative URIs 147 Equality and Comparison 148 String Representations 149 x-www-form-urlencoded 149 URLEncoder 150 URLDecoder 154 Proxies 154 System Properties 155 The Proxy Class 155 The ProxySelector Class 156 Communicating with Server-Side Programs Through GET 157 Accessing Password-Protected Sites 161 The Authenticator Class 162 The PasswordAuthentication Class 164 The JPasswordField Class 164 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 | vii
  • 13. Reading Data from a Server 189 Reading the Header 190 Retrieving Specific Header Fields 191 Retrieving Arbitrary Header Fields 197 Caches 199 Web Cache for Java 203 Configuring the Connection 208 protected URL url 209 protected boolean connected 209 protected boolean allowUserInteraction 210 protected boolean doInput 211 protected boolean doOutput 212 protected boolean ifModifiedSince 212 protected boolean useCaches 214 Timeouts 215 Configuring the Client Request HTTP Header 215 Writing Data to a Server 218 Security Considerations for URLConnections 223 Guessing MIME Media Types 224 HttpURLConnection 224 The Request Method 225 Disconnecting from the Server 229 Handling Server Responses 230 Proxies 235 Streaming Mode 235 8. Sockets for Clients. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Using Sockets 237 Investigating Protocols with Telnet 238 Reading from Servers with Sockets 240 Writing to Servers with Sockets 246 Constructing and Connecting Sockets 251 Basic Constructors 251 Picking a Local Interface to Connect From 253 Constructing Without Connecting 254 Socket Addresses 255 Proxy Servers 256 Getting Information About a Socket 257 Closed or Connected? 258 toString() 259 Setting Socket Options 259 TCP_NODELAY 260 viii | Table of Contents
  • 14. SO_LINGER 261 SO_TIMEOUT 261 SO_RCVBUF and SO_SNDBUF 262 SO_KEEPALIVE 263 OOBINLINE 264 SO_REUSEADDR 265 IP_TOS Class of Service 265 Socket Exceptions 267 Sockets in GUI Applications 268 Whois 269 A Network Client Library 272 9. Sockets for Servers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Using ServerSockets 283 Serving Binary Data 288 Multithreaded Servers 289 Writing to Servers with Sockets 293 Closing Server Sockets 295 Logging 297 What to Log 297 How to Log 298 Constructing Server Sockets 302 Constructing Without Binding 304 Getting Information About a Server Socket 305 Socket Options 306 SO_TIMEOUT 307 SO_REUSEADDR 308 SO_RCVBUF 308 Class of Service 309 HTTP Servers 309 A Single-File Server 310 A Redirector 314 A Full-Fledged HTTP Server 319 10. Secure Sockets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 Secure Communications 326 Creating Secure Client Sockets 328 Choosing the Cipher Suites 332 Event Handlers 336 Session Management 336 Client Mode 338 Creating Secure Server Sockets 339 Table of Contents | ix
  • 15. Configuring SSLServerSockets 343 Choosing the Cipher Suites 343 Session Management 344 Client Mode 344 11. Nonblocking I/O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 An Example Client 349 An Example Server 353 Buffers 359 Creating Buffers 361 Filling and Draining 363 Bulk Methods 364 Data Conversion 365 View Buffers 368 Compacting Buffers 370 Duplicating Buffers 372 Slicing Buffers 376 Marking and Resetting 377 Object Methods 377 Channels 378 SocketChannel 378 ServerSocketChannel 381 The Channels Class 383 Asynchronous Channels (Java 7) 384 Socket Options (Java 7) 386 Readiness Selection 388 The Selector Class 388 The SelectionKey Class 390 12. UDP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 The UDP Protocol 393 UDP Clients 395 UDP Servers 397 The DatagramPacket Class 399 The Constructors 401 The get Methods 403 The setter Methods 406 The DatagramSocket Class 408 The Constructors 409 Sending and Receiving Datagrams 411 Managing Connections 416 Socket Options 417 x | Table of Contents
  • 16. 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 13. IP Multicast. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 Multicasting 444 Multicast Addresses and Groups 447 Clients and Servers 450 Routers and Routing 452 Working with Multicast Sockets 453 The Constructors 454 Communicating with a Multicast Group 455 Two Simple Examples 460 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 Table of Contents | xi
  • 18. 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: • Browsing the Web with HTTP • Writing multithreaded servers • Encrypting communications for confidentiality, authentication, and guaranteed message integrity • Designing GUI clients for network services • Posting data to server-side programs • Looking up hosts using DNS • Downloading files with anonymous FTP • Connecting sockets for low-level network communication • Multicasting to all hosts on the network 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
  • 19. 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. About the Fourth Edition In 1996, in the first edition of this book’s opening chapter, I wrote extensively about the sort of dynamic, distributed network applications I thought Java would make possible. One of the most exciting parts of writing subsequent editions has been seeing virtually all of the applications I foretold come to pass. Programmers are using Java to query database servers, monitor web pages, control telescopes, manage multiplayer games, and more, all by using Java’s native ability to access the Internet. Java in general and network programming in Java in particular has moved well beyond the hype stage and into the realm of real, working applications. This book has come a long way, too. The fourth edition focuses even more heavily on HTTP and REST. HTTP has gone from being one of many network protocols to almost the network protocol. As you’ll see, it is often the protocol on which other protocols are built, forming its own layer in the network stack. There have been lots of other small changes and updates throughout the java.net and supporting packages in Java 6, 7, and 8, and these are covered here as well. New classes addressed in this edition include CookieManager, CookiePolicy, CookieStore, HttpCookie, SwingWorker, Executor, ExecutorService, AsynchronousSocketChan nel, AsynchronousServerSocketChannel, and more. Many other methods have been added to existing classes in the last three releases of Java, and these are discussed in the relevant chapters. I’ve also rewritten large parts of the book to reflect the ever-changing fashions in Java programming in general and network programming in particular. I hope you’ll find this fourth edition an even stronger, longer-lived, more accurate, and more enjoyable tutorial and reference to network programming in Java than the pre‐ vious one. Organization of the Book Chapter1,Basic Network Concepts,explainsindetailwhataprogrammerneedstoknow about how the networks and the Internet work. It covers the protocols that underlie the Internet, such as TCP/IP and UDP/IP. xiv | Preface
  • 20. 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. ExperiencedJavaprogrammersmaybeabletoskimorskipthesetwochapters.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‐ loadinginformationandfilesfromnetworkserversofmanykinds.TheURLclassenables 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
  • 21. 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. Who You Are This book assumes you are comfortable with the Java language and programming en‐ vironment, in addition to object-oriented programming in general. This book does not attempt to be a basic language tutorial. You should be thoroughly familiar with the syntaxofJava.Youshouldhavewrittensimpleapplications.Italsowouldn’thurtifyou’re familiar with basic Swing programming, though that’s not required aside from a few examples. When you encounter a topic that requires a deeper understanding for net‐ work programming than is customary—for instance, threads and streams—I’ll cover that topic as well, at least briefly. However, this book doesn’t assume that you have prior experience with network pro‐ gramming. You should find it a complete introduction to networking concepts and network application development. I don’t assume that you have a few thousand net‐ working acronyms (TCP, UDP, SMTP, etc.) at the tip of your tongue. You’ll learn what you need to know about these here. 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
  • 22. 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. About the Examples Most methods and classes described in this book are illustrated with at least one com‐ plete working program, simple though it may be. In my experience, a complete working program is essential to showing the proper use of a method. Without a program, it is too easy to drop into jargon or to gloss over points about which the author may be unclear in his own mind. The Java API documentation itself often suffers from exces‐ sively terse descriptions of the method calls. In this book, I have tried to err on the side of providing too much explication rather than too little. If a point is obvious to you, feel free to skip over it. You do not need to type in and run every example in this book; but if a particular method does give you trouble, you should have at least one working example. Each chapter includes at least one (and often several) more complex programs that demonstrate the classes and methods of that chapter in a more realistic setting. These often rely on Java features not discussed in this book. Indeed, in many of the programs, the networking components are only a small fraction of the source code and often the least difficult parts. Nonetheless, none of these programs could be written as easily in languages that didn’t give networking the central position it occupies in Java. The ap‐ parent simplicity of the networked sections of the code reflects the extent to which networking has been made a core feature of Java, and not any triviality of the program itself. All example programs presented in this book are available online, often with corrections and additions. You can download the source code from http://www.cafeau lait.org/books/jnp4/. I have tested all the examples on Linux and many on Windows and Mac OS X. Most of the examples given here should work on other platforms and with other compilers and virtual machines that support Java 5 or later. The most common reasons an example may not compile with Java 5 or 6 are try-with-resources and multicatch. These examples can easily be rewritten to support earlier Java versions at the cost of increased verbosity. I do feel a little guilty about a couple of compromises necessitated by the needs of space in a printed book. First, I rarely check preconditions. Most methods assume they are passed good data, and dispense with null checks and similar principles of good code hygiene. Furthermore, I have reduced the indentation to two characters per block and four characters per continuation line, as opposed to the Java standard of four and eight, respectively. I hope these flaws will not be too distracting. On the positive side, these compromises have aided me in making this edition considerably shorter (by several hundred pages) than the previous edition. Preface | xvii
  • 23. Conventions Used in This Book Body text is Minion Pro, normal, like you’re reading now. A monospaced typewriter font is used for: • Code examples and fragments • Anything that might appear in a Java program, including keywords, operators, data types, method names, variable names, class names, and interface names • Program output • Tags that might appear in an HTML document A bold monospaced font is used for: • Command lines and options that should be typed verbatim on the screen An italicized font is used for: • New terms where they are defined • Pathnames, filenames, and program names (however, if the program name is also the name of a Java class, it is given in a monospaced font, like other class names) • Host and domain names (www.hpmor.com) • URLs (http://www.cafeaulait.org/slides/) • Titles of other books (Java I/O) Indicates a tip, suggestion, or general note. Indicates a warning or caution. 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
  • 24. 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!). Request for Comments I enjoy hearing from readers, whether with general comments about this book, specific corrections, other topics they would like to see covered, or just war stories about their own network programming travails. You can reach me by sending an email to [email protected],however,thatIreceiveseveralhundredpiecesofemail a day and cannot personally respond to each one. For the best chance of getting a per‐ sonal response, please identify yourself as a reader of this book. If you have a question about a particular program that isn’t working as you expect, try to reduce it to the simplest case that reproduces the bug, preferably a single class, and paste the text of the entire program into the body of your email. Unsolicited attachments will be deleted unopened. And please, please send the message from the account you want me to reply to and make sure that your Reply-to address is properly set! There’s nothing quite so frustrating as spending an hour or more carefully researching the answer to an inter‐ esting question and composing a detailed response, only to have it bounce because my correspondentsentherfeedbackfromapublicterminalandneglectedtosetthebrowser preferences to include her actual email address. I also adhere to the old saying “If you like this book, tell your friends. If you don’t like it, tell me.” I’m especially interested in hearing about mistakes. This is the fourth edition. I’ve yet to make it perfect, but I keep trying. As hard as I and the editors at O’Reilly Preface | xix
  • 25. workedonthisbook,I’msuretherearemistakesandtypographicalerrorsthatwemissed 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. Using Code Examples This book is here to help you get your job done. In general, if this book includes code examples, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require per‐ mission. We appreciate, but do not require, attribution. An attribution usually includes the title, author,publisher,andISBN.Forexample:“JavaNetworkProgramming,FourthEdition, by Elliotte Rusty Harold (O’Reilly). Copyright 2014 Elliotte Rusty Harold, 978-1-449-35767-2.” If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at [email protected]. Safari® Books Online Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s lead‐ ing authors in technology and business. Technology professionals, software developers, web designers, and business and crea‐ tive professionals use Safari Books Online as their primary resource for research, prob‐ lem solving, learning, and certification training. Safari Books Online offers a range of product mixes and pricing programs for organi‐ zations, government agencies, and individuals. Subscribers have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐ fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐ xx | Preface
  • 26. 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: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) 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 [email protected]. 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, gotthingsrolling,andprovidedmanyhelpfulcommentsalongthewaythatsubstantially 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 socketsandcaughtallpossibleexceptions,andingeneralwrotethecleanest,safest,most exemplary code I could write. John Zukowski found numerous errors of omission, all nowfilledthankstohim.Andtheeagle-eyedAvnerGelbdisplayedanastonishingability to spot mistakes that had somehow managed to go unnoticed by myself, all the other Preface | xxi
  • 27. 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 [email protected] July 5, 2013 xxii | Preface
  • 28. CHAPTER 1 Basic Network Concepts Network programming is no longer the province of a few specialists. It has become a core part of every developer’s toolbox. Today, more programs are network aware than aren’t. Besides classic applications like email, web browsers, and remote login, most major applications have some level of networking built in. For example: • 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
  • 29. 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.Topicscoveredinthischapterincludethenatureofnetworks;theTCP/IPlayer 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 2 | Chapter 1: Basic Network Concepts
  • 30. match any primitive numeric data type in Java. The more bytes there are in each address, the more addresses there are available and the more devices that can be connected to the network simultaneously. Addresses are assigned differently on different kinds of networks. Ethernet addresses are attached to the physical Ethernet hardware. Manufacturers of Ethernet hardware use preassigned manufacturer codes to make sure there are no conflicts between the addresses in their hardware and the addresses of other manufacturers’ hardware. Each manufacturer is responsible for making sure it doesn’t ship two Ethernet cards with the same address. Internet addresses are normally assigned to a computer by the organi‐ zation that is responsible for it. However, the addresses that an organization is allowed to choose for its computers are assigned by the organization’s Internet service provider (ISP). ISPs get their IP addresses from one of four regional Internet registries (the reg‐ istry for North America is ARIN, the American Registry for Internet Numbers), which are in turn assigned IP addresses by the Internet Corporation for Assigned Names and Numbers (ICANN). On some kinds of networks, nodes also have text names that help human beings identify them such as “www.elharo.com” or “Beth Harold’s Computer.” At a set moment in time, aparticularnamenormallyreferstoexactlyoneaddress.However,namesarenotlocked to addresses. Names can change while addresses stay the same; likewise, addresses can change while the names stay the same. One address can have several names and one name can refer to several different addresses. All modern computer networks are packet-switched networks: data traveling on the network is broken into chunks called packets and each packet is handled separately. Each packet contains information about who sent it and where it’s going. The most importantadvantageofbreakingdataintoindividuallyaddressedpacketsisthatpackets from many ongoing exchanges can travel on one wire, which makes it much cheaper to build a network: many computers can share the same wire without interfering. (In contrast,whenyoumakealocaltelephonecallwithinthesameexchangeonatraditional phone line, you have essentially reserved a wire from your phone to the phone of the person you’re calling. When all the wires are in use, as sometimes happens during a major emergency or holiday, not everyone who picks up a phone will get a dial tone. If you stay on the line, you’ll eventually get a dial tone when a line becomes free. In some countries with worse phone service than the United States, it’s not uncommon to have to wait half an hour or more for a dial tone.) Another advantage of packets is that checksums can be used to detect whether a packet was damaged in transit. We’re still missing one important piece: some notion of what computers need to say to pass data back and forth. A protocol is a precise set of rules defining how computers communicate: the format of addresses, how data is split into packets, and so on. There are many different protocols defining different aspects of network communication. For example, the Hypertext Transfer Protocol (HTTP) defines how web browsers and Networks | 3
  • 31. 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. The Layers of a Network Sending data across a network is a complex operation that must be carefully tuned to the physical characteristics of the network as well as the logical character of the data being sent. Software that sends data across a network must understand how to avoid collisions between packets, convert digital data to analog signals, detect and correct errors, route packets from one host to another, and more. The process is further com‐ plicated when the requirement to support multiple operating systems and heterogene‐ ous network cabling is added. To hide most of this complexity from the application developer and end user, the dif‐ ferent aspects of network communication are separated into multiple layers. Each layer represents a different level of abstraction between the physical hardware (i.e., the wires and electricity) and the information being transmitted. In theory, each layer only talks to the layers immediately above and immediately below it. Separating the network into layers lets you modify or even replace the software in one layer without affecting the others, as long as the interfaces between the layers stay the same. Figure 1-1 shows a stack of possible protocols that may exist in your network. While the middle layer protocols are fairly consistent across most of the Internet today, the top and the bottom vary a lot. Some hosts use Ethernet; some use WiFi; some use PPP; some use something else. Similarly, what’s on the top of the stack will depend completely on which programs a host is running. The key is that from the top of the stack, it doesn’t really matter what’s on the bottom and vice versa. The layer model decouples the ap‐ plication protocols (the main subject of this book) from the physics of the network hardware and the topology of the network connections. 4 | Chapter 1: Basic Network Concepts
  • 32. Figure 1-1. Protocols in different layers of a network 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. Figure 1-2. The layers of a network 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‐ The Layers of a Network | 5
  • 33. Random documents with unrelated content Scribd suggests to you:
  • 34. This transportation embraced the so-called "grub" and the conveniences of a covered wagon in which one might ride on easy roads, the expectation being that the passenger would walk up the hills or over difficult tracts. The captain of the outfit, a big, burly freighter, seemed proud to have come from Pike County, Missouri, which he stated had produced the most distinguished men whom he had ever known. It had not been my privilege to meet any of the passengers booked for this Missouri outfit until their arrival at the corral at the appointed hour for starting. In accordance with the custom of the country, each passenger was to furnish his own lodging; in other words, each brought such blankets as were supposed to be necessary for protection at night. My bundle was deposited in the rear wagon, as I was desirous of securing the advantage of an observation car, which would afford an unobstructed view behind us. All the vehicles were ordinary large wagons with canvas covers. THROUGH THE WASATCH
  • 35. My companions in that wagon were two young men from Ohio, each of whom had recently purchased a broncho horse, which he intended to take back to the States and incidentally to use under the saddle, as he might have opportunity, on the Eastward journey. These two quadrupeds were haltered to the rear of the last wagon, which they were expected to follow. That the bronchos might become gradually accustomed to a burden upon their backs, the young men had cinched tightly upon them their bundles of blankets. Thus equipped we rolled out from the city up the terraced slope of "the bench" toward the entrance into Parley's Canyon. (It may be stated that the bench is the narrow level table land, evidently an ancient shore line, that skirts the foothills of those mountains and indicates that during some period the waters in the valley reached that high level). The young men had commented favorably on the docility of their bronchos, which had for a time followed the wagon in a satisfactory manner, and expressed the belief that the animals would afford great comfort on the long trip, by enabling them to take horse-back rides. On entering an area covered with sage brush, a new purpose seemed suddenly to enter the heads of the uncertain bronchos. It may have been inspired by the sight of a little patch of grass on the otherwise arid bench, or it may have been an innate inclination to do something unexpected, an inclination very characteristic of the broncho. Suddenly and almost simultaneously they dropped back on their halters and were soon free and making a flight for the brush. The young men watched their next proceedings with dismay. Having reached an eligible location in an open space, the bronchos at once began a series of evolutions so interesting that the train was brought to a halt. In his favorite pastime of bucking, the broncho has no peer among all the quadrupeds of the earth. It had been my privilege and misfortune to make a personal test of this form of amusement and with the usual results, but never before had I seen it so successfully
  • 36. performed upon inanimate matter, as on this occasion in the sage brush of Utah. The bundles upon the bronchos were light, and were strapped tightly upon them with double girths. The buckers operating closely together apparently entered into a contest, to ascertain which of the two could first relieve himself of his impedimenta. While the train was at rest, the boarders and drivers secured favorable positions, where they might witness the match. Our captain from Pike County, Missouri, broke forth into curses, berating the intelligence of any man who would buy such good-for-nothing creatures, and yet he was the first person to assist in their capture. Again and again the bucking bronchos, facing each other, repeated their vicious plunges, leaping into the air with heads down and backs curved upward, and coming down upon their fore feet, until in some way the bundles were dashed upon the ground and their contents were widely distributed under the animals' feet, after which a sense of victory and freedom seemed to come over them, and only after a long pursuit were they again secured. During the time that I remained with the train, no human being ventured to mount the refractory brutes. The night came on as we turned into camp near the summit of the canyon. The familiar fragrance of fried bacon and coffee was beginning to pervade the atmosphere when the captain from Pike County gave the command to "fall to," which was his method of announcing to the boarders that supper was served. Drawing around the camp fire we faced the same old "Menu" and the same type of battered tin dishes and cutlery that we had become familiar with on our own train, except that the cooking and serving paraphernalia bore evidences of greater antiquity and more violent service. We sat or kneeled upon the ground in a sort of irregular semi- circle. With but few exceptions each man was a stranger to all the others. Each man had a revolver in his belt, and in most cases the
  • 37. men had rifles with their effects in the wagons. Each was curious to know where the other fellow came from, and without much ceremony the blunt, but good-natured question, "Where do you hail from?" was propounded to one's neighbor in the circle. The roster was soon completed, and before we left the camp fire my record showed that one of the party had recently closed his apprenticeship under Morgan, the raider; another, an ex-confederate, was from Old Virginia; one was from the Sandwich Islands; one from New Hampshire; one each from Arkansas, South Carolina, Michigan, and Wisconsin, and two were from Missouri. Our cook was a young Snake Indian, but the rest of the crew had not yet disclosed any facts concerning their life-history. From the members of such a miscellaneous gathering there came naturally some sparring and good-natured reviling tinged at times with acrimony, for the bitterness of the Civil War had not yet materially lessened. But after the first parry of words all realized that they were now comrades for mutual protection. A quiet place was soon found up the mountain side, and wrapping my blanket around me I watched the bright stars until I fell asleep. In the morning we had a touch of camp life that was calculated to bring to the surface that trait of character which would manifest itself in an hour of trial. The captain had been heard to shout from a distant point, where he was attending to a mule, to ask the young Indian cook why in h—l he didn't call breakfast, as it was time for the train to pull out. The brush fire had burned long enough to have boiled coffee many times, but the Snake Indian seemed to be wandering abstractedly round the wagons as if searching for some missing article. As the Captain approached and again demanded an explanation for the delay, the boy informed him, in the few English words at his command, that some one had taken the bacon. He declared that the great slab of meat referred to had on the night
  • 38. before been placed in the covered mess box at the tail end of the wagon. The Captain again swore, and, with the air of a commander of men, proceeded in his endeavors to solve the mystery. Two mules had been picketed all night near the wagon, and the Captain, doubtless aware of the omnivorous habits of those amalgamated beasts, examined their surroundings, and observed squarely under the fore feet of one an elevated surface that appeared suspicious. He backed the mule, and with his foot scraped away an inch or two of dirt, beneath which he struck the stratum of bacon, disfigured somewhat by the heavy pressure of the animal's hoofs, but nevertheless recognizable as bacon. The mule had evidently, at some time during the night, lifted the lid of the mess box with his nose, and seizing the bacon with his teeth had undertaken the task of eating it, but finding some coarser food better suited to his incisors had abandoned the bacon in disgust, dropped it upon the ground, pawed dirt upon it, and then planted his feet on the pile. "Here's your bacon," said the Captain, with an oath, and a sneer of superiority. "Now hurry up that breakfast." This event occurred prior to the development of our present theory of germs and the sterilization of food, so vexing to modern epicures. An empty stomach needs no appetizing sauce. When I have listened to adverse criticisms concerning dishes served at elaborately prepared banquets, I have more than once recalled that breakfast of bacon and coffee prepared by a Snake Indian cook in the Wasatch Mountains. There was no bacon to be wasted. On those clear frosty nights it was a pleasure to creep up the mountain side, and beneath the open starry sky to roll up in a blanket and be lulled to sleep by the music of streams rushing down those canyons. Strange as it may seem, no colds ever resulted from this life in the open air. Every breath inhaled in the waking hours or while asleep, was of pure air not vitiated by exhalations from the
  • 39. lungs of others, nor breathed in part over and over again. This immunity from colds is also true under some conditions that might seem seriously dangerous to one accustomed only to the comforts of civilized life. An example of this was afforded on Tuesday evening, the 18th of September, when we reached Quaking Asp Hill, near the summit of the Divide. A fine driving rain, which extinguished our fires, began to fall at dusk, before we had finished our bacon and coffee, and there were indications of a cold and heavy storm. That he might the better protect himself against the elements, the Sandwich Islander entered into negotiations to double our blankets, a proposal that was promptly accepted, as he was provided with one which was waterproof to place on the wet ground. Each of us had the regular double army blanket and overcoat. This was not the first rainy night that I had spent without a roof above me, but it was certainly the wildest. As the night advanced and the wind was blowing violently, we naturally turned our feet toward the gale and loaded the edges of the blankets with rocks to hold them in place. We then settled down to await the time when the water would penetrate our clothing. Fortunately the rain turned into a driving snow storm. The gale veered round and came from the North, increasing in intensity, and although our blankets were frozen, the wind now coming toward our heads, pressed down between us and lifted the covering like a balloon until it found escape at our feet, while the covers waved and flapped in the air. It seemed too late to reverse our position, but we held tightly to the coverings until the accumulating snow gradually weighted them down. The wind also became more moderate toward midnight, but the snow continued to fall rapidly until after we fell asleep. My companion and I had "spooned" as closely as possible that we might share each other's warmth, and if one was inclined to turn over his partner promptly responded. I awoke after daylight, conscious of the heavy weight resting upon us. Opening my eyes I looked upward through the white funnel
  • 40. in the snow which had been formed by our breaths, melting the falling flakes, but everything was still. The storm had ceased, and although the sun had not yet risen above the mountain peaks, we saw that a bright morning was dawning upon us. A council with my companion led us to lift the blankets with care, and remove the weight of snow that covered us. After rising to a sitting position, it was discovered that we were not alone. Here and there at different points were undulations on the brilliant white surface of the snow. In one end of each of these was the funnel which told us that the warm breath of the sleepers had also preserved for them an open view of the sky above. Must we, as first-class boarders, dig the walks through the snow and build the fire? We decided in the negative, and accordingly called the camp to service. One by one snow mounds were lifted and living beings arose from beneath the thick white mantle. The Captain had slept in his wagon, but he promptly assumed command. Preparations were soon under way for breakfast, and the stock was cared for. Nearly eight inches of snow had fallen. Not a track was visible to guide us along the road during the greater part of the following day, but as we descended into the valleys, there was but little snow upon the ground, and that disappeared rapidly. Not one of our party "caught cold." The days rolled by until one morning after we had passed Fort Bridger, we met our long ox train moving Westward. It halted until I could transfer my baggage, after which I bade a hearty farewell to the fellow travelers in the boarding-house train. Taking possession of a good saddle horse, I started Westward again with our own long caravan. This brings us to new experiences. It was no trifling matter to conduct a long ox train up and down the mountain canyons, as will be discovered later. This was not because it was difficult to find the trail, but it was because the trail itself was often difficult. It was the principal highway through the ranges of mountains, and from Fort
  • 41. Bridger westward was the regular stage road, yet it was often steep and dangerous. Captain Whitmore and his men were somewhat weary, having had a hard trip, and my services, therefore, seemed to be very welcome. The provisions were running low. Sugar for coffee and soda for bread were long since exhausted. In fact, the stock of food was reduced to flour, bacon, and a little coffee. Milk or vegetables were never obtainable, and canned goods had not come into use. Two or three men who were with the train had endeavored to incite the others to rebellion, and appearing before Captain Whitmore told him substantially in the words once addressed to Moses of the time when back in the States, "They sat by the flesh pots and did eat bread to the full," but now they could not get a square meal in the wilderness. It appears that these mutineers were recognized by their companions as wasteful, shiftless men, too proud and lazy to work when at home. From Whitmore's rulings there would be no appeal in that country, except to the law of force. There were no cucumbers, melons, leeks, or onions in that wilderness. Bacon or unleavened bread or death was the alternative, unless they could hustle for wild game. Regarding the subsequent careers of the three men above referred to as an object lesson, it may be interesting to note the fact that to the end of their lives none appeared ever to be in a position to assist another, or to keep want from his own door. It was along this road that we fell in with Captain Chipman's ill- starred train of Mormon emigrants. Mingling with the Pilgrims in their camp, I became interested in a young Englishman named S. W. Sears, whose history is full of adventures and chequered with varied experiences. Although then but twenty-two years of age, he was chaplain of the train; for be it known that notwithstanding the sins ascribed to the Mormons, they maintained regular devotional services in camp as well as temple. Sears' wife had died on their westward pilgrimage six months after their marriage and was buried on the banks of the North Platte.
  • 42. A few days later their train was attacked by Indians who captured 300 of their horses and oxen. The emigrants saved enough of their stock to move their wagons in divisions until they escaped from the hostile Indian territory. Sears became prominent both as a missionary of the Mormon faith and in commercial life. Two wives survived him, one of whom was the adopted daughter of the distinguished Daniel H. Wells and was born in a wagon near the entrance to the city at the termination of her mother's long journey across the plains. Travel, like politics, makes strange bedfellows, and especially that kind of travel in which all companions must, from necessity, mingle on a common level, eat their simple rations by the same camp fire, and sleep side by side beneath the same open sky. This observation is suggested by a night spent in camp near Bear River. Our ox train had just forded that rocky stream, to avoid the excessive toll which was demanded for the privilege of crossing upon the new bridge. Before going into camp near by, the Captain of a little train that had preceded us rode his horse rapidly into the stream in his effort to head off some intractable mules. The horse stumbled over some stones and fell upon its knees, throwing the rider over his head in a fairly executed somersault into the water. The feat evoked hearty applause from those who were fortunate enough to witness it. Now it happened that among the men with our train was a modest but vigorous young man named Ferdinand Lee, whom I had known quite well before he had served his full time during the war just ended as a private in the Second Wisconsin Regiment, which distinguished itself as part of the famous Iron Brigade. After supper I walked up the bank of the stream with Ferd, which was the name by which Lee was familiarly known, and we soon encountered a group of men composed of stragglers from two
  • 43. small parties that were camping near by and who like ourselves had gravitated toward the best camp fire. "Was it your Captain what made that h—l of a dive from his hoss into the river?" asked a tall, black-whiskered Southerner of a small, red-headed chap, who we learned later was known as Sandy. "I reckon it war. Didn't he do it all right?" was the reply. "What's your name, anyhow?" he continued. "Well, it don't make much difference, but these fellows call me Shorty, and I was wondering if that Captain ever rid a hoss before." "Guess he has, because he says he was in the army and raided in Kentucky with the Rebs," replied Sandy. "Those Kentuckyans think they can ride, you know." And with this he took a seat upon a little rock, lighted a pipe, and others followed his example. "I guess you're a Yank," said Shorty. "Well, I reckon I am," said Sandy, "and while we are guessing I would put you down for a Johnny Reb." A frown came over Shorty's face, when he said, with some bitterness, "You think the Kentucky boys can't ride much, hey?" "I recollect hearing them tell about your General Winne, when he and some of his boys here were pretty close together near the Wilderness Tavern. He did the same thing in the water of Flat Run that your Captain did in Bear River." "War you in the Wilderness two years ago?" asked Sandy. "I was in the Iron Brigade of Maryland, sir." "Then I reckon you have seen General Winne. But don't you think you fellows did a lot of careless shooting around there?"
  • 44. "Wa'al, we pumped some lead the best we knew how, but were you careless enough to be standing around in that country when shooting was going on?" asked Shorty. "There's a bullet inside of me that once in a while tells me that mebbe I wasn't in jest the right place." "What company were you in?" asked Shorty. "I was fooling around a little with the Twentieth Maine," was the reply. Ferd Lee had been a quiet but interested listener. One of our boys, without turning his head remarked that Lee just behind him did some business in the Wilderness. "Lee? That's a good Virginia name. But you were not in our Brigade, were you?" "No," replied Ferd. "I loafed around a few years with the Second Wisconsin in the Iron Brigade." Shorty instantly rose to his feet, and approaching Ferd said, "I have surely met you before, sir. Although I hate the Yankees, I respect the bravery of the men in your Brigade, and I want to shake your hand." Ferd rose, took the hand of the Confederate veteran, and they looked into each other's eyes as the firelight flickered in their faces, when Ferd said, "No men ever fought better than yours did." The Iron Brigade had earned its name through the valor and inflexible courage of its men on many battle-fields, and its Second Wisconsin Regiment had borne an honorable part in its achievement. Thus, for the first time since they had met in conflict on the battle-fields of Virginia, those veterans again confronted each other.
  • 45. True, the war was over, but it had left its bitterness. Nevertheless, like other brave men, they were impelled to respect the soldiers on the opposing side, whose deeds had been as valorous as those of any heroes immortalized in poetry and song. Until late that night, by the peaceful camp fire on the banks of Bear River, the boys rehearsed the thrilling events in which they had participated in the effort to shed each other's blood. As would naturally be supposed, Captain Whitmore, as the opportunity presented itself, gave me from time to time the story of his experience thus far during his trip. One event, the particulars of which were confirmed by his men, seemed to be so interesting that I asked him to describe it again to another party of travelers at our night's camp. It appears that one afternoon his ox train was slowly crawling along near the north slope of a low range of hills west of Julesburg. A family of emigrants from Illinois consisting of a man, his wife, a grown son and a daughter about eighteen years of age, and a couple of assistants, had accompanied the train from the last military post. As these emigrants had horse teams, which travel somewhat faster than oxen, they were accustomed to driving half a mile or more in advance of the big train, although they had been warned of the hazard; but there they were on that fatal day to receive unaided the brutal raid of a band of Indians which swooped down from the hills. John Wilson on horseback and Mr. Stone of Iowa on foot were out in opposite directions for a hunt. Simultaneously with the attack on the emigrant's wagons, Wilson was seen racing down a valley toward the train pushing his horse to the top of its speed, and in close pursuit was a band of mounted savages yelling like demons. At the same moment Mr. Stone, who was in full view not a mile distant, became the object of an attack from still another detachment of warriors also on horse-back. The train was corralled in a circle for defense as speedily as possible. In the meantime Stone displayed marvelous tact and coolness. He was armed with a Henry repeating rifle loaded with sixteen cartridges, and, as was the usual custom with all hunters, he also carried in addition a case of loaded cartridges. On discovering the rapid
  • 46. approach of the savages he hastened to the top of a little mound that was near by and dropped upon his face. Pursuing their usual tactics the Indians in single file rode swiftly in a circle round and round the apparently doomed Iowan, gradually approaching their victim, who would soon be within range of their arrows. Stone remained quiet for a few moments until his enemies, filing rapidly by the line of his aim as they passed, were within fairly safe range, and then his rifle, directed with careful precision, opened up a series of discharges such as they probably had never before seen, for the Henry was a newly invented weapon and the savages doubtless intended to close in as soon as the rifle should be discharged. In Stone's first series of shots he emptied three saddles of their riders and wounded two horses. While the savages then swung outward for a moment, time was given him to refill the chamber of his rifle with fresh cartridges when at once he renewed his defensive tactics, with results that were startling. The Indians who were still in action seemed to be perplexed by the strange, persistent weapon that was turned upon them, and slowly withdrew. Stone retreated toward the train and was soon under cover of its rifles. The emigrant's party fared badly. All were slaughtered except the young girl, who was captured alive and was taken off with the horses and the plunder from the wagons. I learned later that she remained in captivity until the following spring, when she was restored to the military and thence transported to her former home. Wilson reached a point where his exhausted horse, which had fully shared in the panic, fell prostrate to the ground and never again rose to its feet. The train, now well fortified and defended, escaped further loss. It may be remembered, as was narrated in another chapter, that in the early days of our expedition and away back in the little village of Churchville, Iowa, a young girl disguised in boy's apparel succeeded in joining the train and became an assistant to the man and his wife who were the cooks for the outfit. After our little party proceeded in advance of the big train from Nebraska City we
  • 47. received no definite tidings concerning its progress until the meeting near Bridger, which has just been described. It was therefore a great surprise, on now again reaching the train, to learn that the girl had thus far shared the hardships and perils of the entire journey. What would lead a young, apparently modest, and prepossessing country maid to embark on a long trip with a body of strangers destined to a far away Mormon town in the mountains? Before being permitted to proceed from Nebraska City, it appears that she gave out some statements concerning her history. From these it transpired that she was an orphan about nineteen years of age. She had a lover, who, she confidently believed, was in Salt Lake valley. It seemed to be the old story of a trustful, confiding girl and possibly a recreant wooer, in whom she still had unbounded faith. She was intelligent for one of her years and was apparently sincere and thoroughly in earnest. "Yes, he is right there in the valley, and he does not know that I am going to meet him," she said. But, young girl, there are hundreds of canyons and branch canyons reaching out from the valleys around Salt Lake basin. Many of them are seldom trodden. Some, difficult of access, invite the adventurer to their remotest nooks, where the fortune-hunter would seek for gold or silver. How will you find him? "Hope is a lover's staff," and on that frail support her future rested. She had come to be known to the boys with the train, many of whom had been soldiers, as the child of the regiment. We well remember how she then appeared as she was about to enter practically alone into the turbulent life of the little city of Salt Lake, for it must be understood that the train men must there separate, and while she might receive some assistance, she must fight her own battles. If any old resident of Churchville, Iowa, knew a bright, handsome young girl of medium height with dark hair and big dark eyes who in the spring of sixty-six suddenly disappeared from that
  • 48. village he may get this little glimpse of her history. Her real name was always withheld. The name by which she was known to our boys would have no significance to her former acquaintances. I never saw her again after the train reached the city. She suddenly vanished in the whirlpool of western life. It was reported that a young girl answering the description of our whilom ward was one morning seen riding alone on horse-back up City Creek canyon, to which valley hundreds of men had that year been attracted by rumors of gold discoveries. And so must end a tale half-told. During those days I was assisting on horse-back in various ways, and at times conducting the long train round the sharp curves in the canyons. Six or eight yokes of oxen drawing two large wagons coupled together is a long thing in itself, stretching out perhaps 150 feet. It may run beautifully on a straight road, but in rounding a short bend in a narrow roadway, where the inside of the bend is on the edge of a precipice, the tendency is to bring the wagons dangerously near the brink. On the third of October, our train was winding along the narrow roadway among the cliffs of Silver Creek Canyon. Looking across a deep ravine before us we observed the last wagon in the train that was crawling along in advance of ours, to be encroaching on the edge of a precipice, and in a moment a wheel slipped over the bank. The great prairie schooner capsized, breaking the tongue, detaching the wagon from the teams, and turned upside down. Down, down it rolled, repeatedly bounding over rocks and through bushes, until it found a resting place quite out of sight near the bottom of the canyon. As we approached the scene of the catastrophe an odor, recognized by experienced drivers as of whiskey, came from the wreck of the wagon. We passed on as soon as the way could be opened. A number of men from the delayed train seemed inspired with a benevolent impulse that led them to assist in saving
  • 49. something from the wreck, and were soon clambering down the rocks toward the spot from which the fragrance came the strongest. We learned nothing of the final results of the work of this salvage corps. Their voices, which came up from the hidden depths, indicated that they had found something, and the odors were evidence that enough fire water had been spilled to have made a whole tribe of the solemnest Indians hilarious. On the afternoon of the same day, in going down a steep descent in the same canyon, the failure to fasten the brake on one of our wagons caused the two that were coupled together to gain so much headway that they pressed the ox teams into a frightened mass. The breaking of the wagon tongue turned the wagons down a long steep slope leaving the road more than five hundred feet above. We now had our own troubles. After taking a survey of our wreck, which consisted of a load of miscellaneous merchandise and a wagon in trail, on which was a heavy boiler, I rode back to the little settlement of Wanship for articles needed in repairs. In the meantime the train was corralled further down the canyon, and the stock wandered up the mountain valleys. In the morning many oxen were missing which it was my pleasure to assist in finding, for I loved the hills. Mounting a horse, I ascended a ravine and crossed two or three mountain spurs where it was hoped a glimpse of the strays or their tracks might be obtained. Looking from a concealed position across a deep valley, I observed on the opposite slope an animal which I became satisfied was a mountain sheep, the Big Horn. I had seen many specimens of the various animals and birds indigenous to the West, but never a mountain sheep, except in captivity. They are wary animals, and like the chamois of the Alps are at home on the rocky cliffs. I must be cautious. My horse was fastened behind me, out of view, down the mountain slope. My Henry rifle was in good condition. Lying on my
  • 50. face while carefully sighting through the underbrush, I felt myself to be absolutely safe from discovery. Calculating the distance as accurately as possible, a careful aim was taken, but the bullet fell far short of the mark, striking the rocks away beneath. The animal was evidently unconscious of my death-dealing purpose, and nestled quietly half-concealed in a growth of underbrush. Another shot was fired, when it became evident that my Henry was not of sufficiently long range to reach the game. The opportunity before me was too rare to be sacrificed without effort. Therefore, after tying a silk handkerchief to a limb to mark the trail to my horse, I skirted the spur of the mountain, on foot, slowly descended into the ravine, and laboriously clambered up the other side. The time and effort expended in accomplishing the ascent to the other side made it clear that I had been greatly deceived in the distance, but I was happy to make any physical effort to secure a mountain sheep. The last quarter of a mile must be made with exceeding caution, because the quick ear of the Big Horn would catch any unusual sound. After more than an hour of vigorous but cautious climbing, an eligible point was reached, toward which my course had been directed, and with rifle ready to fire on the first sight of the game, my head was slowly raised above a projecting rock in confidence that the game had not ascended the mountain. There it was in full view, not more than a hundred yards distant. It certainly had horns, but the sight of half a dozen ordinary sheep huddled together in the background revealed to my obtuse consciousness the fact that my game was a ram, which was guarding a little flock of domestic sheep similar to those with which we are all familiar. Shall victory be wrested from defeat? Our boys needed meat, and I could tumble a sheep's carcass down the mountain side. Conflicting emotions throbbed within my breast, until approaching the sheep I was confronted by a tough-looking mountaineer, after which I cared less for mutton.
  • 51. "What are ye doin' up here?" was his interrogatory. "Oh, I'm out a hunting." "What kind of game are ye after?" he asked. "Oh, any nice game that needs a good shot." I noticed that the stranger had a revolver at his side, and in a few moments another slouched-hat individual emerged from a little hut in a side ravine. "What kind of a rifle is that you've got?" "It's a Henry." "I've hear'n of one but never seen one before. Lemme see it," said the mountaineer. He took the gun from me and carefully looked it over. "Where are you from, anyhow?" he asked, without taking his eyes from the gun. I gave the name of the town without any additional facts. Continuing, he said, "I was there once. I lived up in Bark Woods awhile. Do you know where Pumpkin Holler is, just beyond Hebron?" "Yes." "Did you ever know Jim Roach, who hauled logs to Joe Powers' saw mill at Hebron?" "The holler is several miles from my town, but I think I have heard the name," I replied. "Didn't you ever hear of Jim Roach's nephew Ben?" he asked. "Maybe I have," was the answer. "Well!" said the mountaineer, "I'm him."
  • 53. I CHAPTER XXVIII Some Episodes In Stock Hunting N later years, through the influence of one of its ambitious citizens, the little settlement referred to in the last chapter as Pumpkin Holler had come to be known by the more classic if less appropriate name of Rome. There was, however, nothing in my recollection of that sleepy crossroads or of its alleged former citizen, Benjamin Roach, and his friend, that would tempt me to remain longer than necessary in their mountain fastness, nor did I invoke their aid or inform them that a number of our cattle had strayed up the adjacent valleys. It was the current belief that some men who lived in those parts, having no other visible means of support, were inclined to care for stray stock, and pursued that avocation as a pastime chiefly in their own interest. As soon, therefore, as the Henry rifle was again in my hands, I retreated down the mountain side through the thickets of underbrush and then up the other side of the valley. The silk handkerchief, which had been left on the opposite cliff as a landmark, served a good purpose as it enabled me to reach my horse by a fairly direct course. The lengthening shadows on the mountain slopes were a warning that I should speedily proceed to the business of hunting cattle. It was nearly sunset when I caught a glimpse of oxen nearly a mile distant and partly concealed by a grove near which they were grazing. Being confident that they were part of our missing stock I started to reach them. The steep, rough, and rocky mountain slope which was hurriedly descended in the quest was ill adapted to horse-
  • 54. back riding and the pathless groves of underbrush proved to be serious obstructions to progress. Becoming entangled in the unyielding branches the stock of my rifle was broken squarely off, and a few new holes in size beyond the skill of the novice to repair, were punched through my garments in places where additional holes were unnecessary. On emerging into an open space, it was found that both horse and rider had received a few scratches, and the bridle was broken. All these mishaps were ordinary incidents to which any stock hunter is subject if he is inclined to wander unnecessarily into new and untrodden paths, but the big whip, the favorite artillery of the cowboy, was saved. Our wayward oxen were finally rounded up far up a valley where the grass grows the greenest, but with temper not unlike that of men they evidently preferred the freedom of the mountains to a condition of servitude. Apparently understanding my purpose they scattered in a wild race to avoid, if possible, being again brought under the heavy yoke, but were finally brought to the corral down the canyon. Our troubles were not yet ended. On the following day two more wagon wheels collapsed on a steep slope. The train was again halted. The stock was turned out upon the range with its numerous ramifications of ravines and thickets, and before the morning dawned many of the animals were out of our sight. We were not traveling on schedule time, yet this delay brought forth some outbursts of profanity from those who were accustomed to swear, all of which produced no effect on the cattle scattered up the valleys. On the following morning there began another series of experiences in hunting stock, which afforded a fair illustration of the manner in which the Western Mountaineer of that day lived and tried to sleep. Taking a heavy horse, which unfortunately was not adapted to mountain climbing, I started alone southward up a long side ravine directed in part by the tracks of the oxen. Having reached rather a high altitude, and desiring to obtain a better view of the surrounding
  • 55. Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade 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. Let us accompany you on the journey of exploring knowledge and personal growth! textbookfull.com