100% found this document useful (1 vote)
19 views

Java Network Programming Fourth Edition Elliotte Rusty Harold download

The document provides information about the fourth edition of 'Java Network Programming' by Elliotte Rusty Harold, published by O'Reilly Media. It includes details on the book's content, such as basic network concepts, streams, threads, internet addresses, and secure sockets, among others. Additionally, it offers links to other related ebooks available for instant download.

Uploaded by

olowububer6y
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
19 views

Java Network Programming Fourth Edition Elliotte Rusty Harold download

The document provides information about the fourth edition of 'Java Network Programming' by Elliotte Rusty Harold, published by O'Reilly Media. It includes details on the book's content, such as basic network concepts, streams, threads, internet addresses, and secure sockets, among others. Additionally, it offers links to other related ebooks available for instant download.

Uploaded by

olowububer6y
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Java Network Programming Fourth Edition Elliotte

Rusty Harold download

https://ebookname.com/product/java-network-programming-fourth-
edition-elliotte-rusty-harold/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

XML in a nutshell 3rd ed Edition Elliotte Rusty Harold

https://ebookname.com/product/xml-in-a-nutshell-3rd-ed-edition-
elliotte-rusty-harold/

Linear programming and network flows Fourth Edition M.


S. Bazaraa

https://ebookname.com/product/linear-programming-and-network-
flows-fourth-edition-m-s-bazaraa/

Java Programming 5th Edition Joyce Farrell

https://ebookname.com/product/java-programming-5th-edition-joyce-
farrell/

Scott 2007 Standard Postage Stamp Catalogue Vol 6


Countries of the World So Z 163rd Edition James E.
Kloetzel

https://ebookname.com/product/scott-2007-standard-postage-stamp-
catalogue-vol-6-countries-of-the-world-so-z-163rd-edition-james-
e-kloetzel/
601 great scrapbook ideas 1st ed Edition Memory Makers
Books

https://ebookname.com/product/601-great-scrapbook-ideas-1st-ed-
edition-memory-makers-books/

On Percs Facebooking While Intoxicated 1st Edition Mike


Rainey

https://ebookname.com/product/on-percs-facebooking-while-
intoxicated-1st-edition-mike-rainey/

If Not Now When Writings in Defense of Europe 1st


Edition Mathijs Koenraadt

https://ebookname.com/product/if-not-now-when-writings-in-
defense-of-europe-1st-edition-mathijs-koenraadt/

Research for Development A Practical Guide 1st Edition


Sophie Laws

https://ebookname.com/product/research-for-development-a-
practical-guide-1st-edition-sophie-laws/

A Slice of Organic Life 1st Edition Sheherazade


Goldsmith

https://ebookname.com/product/a-slice-of-organic-life-1st-
edition-sheherazade-goldsmith/
Handbook of Diabetes 4th Edition Rudy Bilous

https://ebookname.com/product/handbook-of-diabetes-4th-edition-
rudy-bilous/
FOURTH EDITION

Java Network Programming

Elliotte Rusty Harold


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
also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editor: Meghan Blanchette Indexer: Judy McConville
Production Editor: Nicole Shelby Cover Designer: Randy Comer
Copyeditor: Kim Cofer Interior Designer: David Futato
Proofreader: Jasmine Kwityn 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.
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
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


Chapter 1, Basic Network Concepts, explains in detail what a programmer needs to know
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.
Experienced Java programmers may be able to skim or skip these two chapters. However,
Chapter 4, Internet Addresses, is essential reading for everyone. It shows how Java pro‐
grams interact with the Domain Name System through the InetAddress class, the one
class that’s needed by essentially all network programs. Once you’ve finished this chap‐
ter, it’s possible to jump around in the book as your interests and needs dictate.
Chapter 5, URLs and URIs, explores Java’s URL class, a powerful abstraction for down‐
loading information and files from network servers of many kinds. The URL class enables
you to connect to and download files and documents from a network server without
concerning yourself with the details of the protocol the server speaks. It lets you connect
to an FTP server using the same code you use to talk to an HTTP server or to read a file
on the local hard disk. You’ll also learn about the newer URI class, a more standards-
conformant alternative for identifying but not retrieving resources.
Chapter 6, HTTP, delves deeper into the HTTP protocol specifically. Topics covered
include REST, HTTP headers, and cookies. Chapter 7, URLConnections, shows you how
to use the URLConnection and HttpURLConnection classes not just to download data
from web servers, but to upload documents and configure connections.
Chapter 8 through Chapter 10 discuss Java’s low-level socket classes for network access.
Chapter 8, Sockets for Clients, introduces the Java sockets API and the Socket class in
particular. It shows you how to write network clients that interact with TCP servers of
all kinds including whois, dict, and HTTP. Chapter 9, Sockets for Servers, shows you
how to use the ServerSocket class to write servers for these and other protocols. Finally,
Chapter 10, Secure Sockets, shows you how to protect your client-server communica‐
tions using the Secure Sockets Layer (SSL) and the Java Secure Sockets Extension (JSSE).
Chapter 11, Nonblocking I/O, introduces the new I/O APIs specifically designed for
network servers. These APIs enable a program to figure out whether a connection is
ready before it tries to read from or write to the socket. This allows a single thread to
manage many different connections simultaneously, thereby placing much less load on
the virtual machine. The new I/O APIs don’t help much for small servers or clients that
don’t open many simultaneous connections, but they may provide performance boosts
for high-volume servers that want to transmit as much data as the network can handle
as fast as the network can deliver it.

Preface | xv
Chapter 12, UDP, introduces the User Datagram Protocol (UDP) and the associated
DatagramPacket and DatagramSocket classes that provide fast, unreliable communi‐
cation. Finally, Chapter 13, IP Multicast, shows you how to use UDP to communicate
with multiple hosts at the same time.

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
syntax of Java. You should have written simple applications. It also wouldn’t hurt if you’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. Please realize, however, that I receive several hundred pieces of email
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
correspondent sent her feedback from a public terminal and neglected to set the browser
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
worked on this book, I’m sure there are mistakes and typographical errors that we missed
here somewhere. And I’m sure that at least one of them is a really embarrassing whopper
of a problem. If you find a mistake or a typo, please let me know so I can correct it. I’ll
post it on the O’Reilly website at http://oreil.ly/java_np_errata. Before reporting errors,
please check one of those pages to see if I already know about it and have posted a fix.
Any errors that are reported will be fixed in future printings.

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, and ISBN. For example: “Java Network Programming, Fourth Edition,
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,
got things rolling, and provided many helpful comments along the way that substantially
improved the book. Dr. Peter “Peppar” Parnes helped out immensely with Chapter 13.
The technical editors all provided invaluable assistance in hunting down errors and
omissions. Simon St. Laurent provided crucial advice on which topics deserved more
coverage. Scott Oaks lent his thread expertise to Chapter 3, proving once again by the
many subtle bugs he hunted down that multithreading still requires the attention of an
expert. Ron Hitchens shone light into many of the darker areas of the new I/O APIs.
Marc Loy and Jim Elliott reviewed some of the most bleeding edge material in the book.
Timothy F. Rohaly was unswerving in his commitment to making sure I closed all my
sockets and caught all possible exceptions, and in general wrote the cleanest, safest, most
exemplary code I could write. John Zukowski found numerous errors of omission, all
now filled thanks to him. And the eagle-eyed Avner Gelb displayed an astonishing ability
to spot mistakes that had somehow managed to go unnoticed by myself, all the other

Preface | xxi
editors, and the tens of thousands of readers of the first edition. Alex Stangl and Ryan
Cuprak provided further assistance with spotting both new and lingering mistakes in
this latest edition.
It isn’t customary to thank the publisher, but the publisher does set the tone for the rest
of the company, authors, editors, and production staff alike; and I think Tim O’Reilly
deserves special credit for making O’Reilly Media absolutely one of the best houses an
author can write for. If there’s one person without whom this book would never have
been written, it’s him. If you, the reader, find O’Reilly books to be consistently better
than most of the dreck on the market, the reason really can be traced straight back to
Tim.
My agent, David Rogelberg, convinced me it was possible to make a living writing books
like this rather than working in an office. The entire crew at ibiblio.org over the last
several years has really helped me to communicate better with my readers in a variety
of ways. Every reader who sent in bouquets and brickbats for previous editions has been
instrumental in helping me write this much-improved edition. All these people deserve
much thanks and credit. Finally, as always, I’d like to offer my largest thanks to my wife,
Beth, without whose love and support this book would never have happened.
—Elliotte Rusty Harold
elharo@ibiblio.org
July 5, 2013

xxii | Preface
CHAPTER 1
Basic Network Concepts

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
Exploring the Variety of Random
Documents with Different Content
nine and ten o'clock. I will not be positive about that. It might have
been earlier, and it might have been later. I think, though, between
nine and ten o'clock in the morning.
Q. Did he state exactly where he found him?
A. He said he had followed him beyond Sharpsburg, and dismounted
from his carriage, and had marched on foot with him for some
distance. Had communicated the order that he has stated. Had
conversed with him for some time, and that General Brinton had
refused to return to Pittsburgh.
Q. Did he say anything about his refusal to join Colonel Guthrie?
A. While I said return to Pittsburgh I meant to join Colonel Guthrie—
that was implied. That after they joined, that is, it was in our minds,
after they had united their commands, that they were to return to
Pittsburgh; but when I said refused to return to Pittsburgh, I meant
refused to join Colonel Guthrie, or rather to execute the order that
Colonel Norris had to carry.
Q. Did he say anything about the condition of General Brinton's
troops?
A. Perhaps he may have mentioned it in a general way, but 1 do not
recollect that he specified it particularly.
Q. That was not spoken of?
A. I think not. At least that did not impress itself on my mind, if it
was mentioned.
Q. Anything said about getting provisions to them?
A. Well, there probably was, but I am not prepared to say what it
was—that was a matter that was paramount in all our minds, the
matter of provisions for the troops had been concerning me,
particularly, from the evening before, and continued to concern me
until the next evening, until I secured some provisions and got them
to the troops.
Q. Is that all that you know in relation to what occurred between
Colonel Norris and General Brinton?
A. That is all, I believe, sir.
Colonel Norris: I would like to say, when I got back to the hotel, Mr.
Cassatt was there, and I believe Mr. Bennett, of Allegheny, and we
had a conversation then about supplying General Brinton's command
with provisions and ammunition, and an arrangement was there
made, I myself giving the directions where he was to convey the
provisions to him, and that provisions did ultimately reach him. That
conversation was heard, I believe, by Colonel Hassinger.
Colonel Smith: If I may be permitted—I was speaking of the time I
met Colonel Norris. I was present at that conversation, at the
Monongahela house, and can verify what the colonel said at that
time.

Colonel D. L. Hassinger, sworn:

By Mr. Lindsey:

Q. You understand, I believe, the subject of evidence to-night. Will


you go on and state what knowledge you have on the subject?
A. I was at the Monongahela house when Colonel Norris and Major
Stewart returned, and I heard just about—he reported that he had
caught up with General Brinton on his way out beyond Sharpsburg
bridge, that he got out of the carriage and walked along, and had
the conversation, and spoke about the order which had been sent to
him through Captain Aull, and he said he gave him the substance of
the order, and General Brinton had refused to obey him.
Q. Can you give the language of Colonel Norris—the exact words
that Colonel Norris used?
A. Well, I don't know that I can, exactly. I do not recollect that part
of it.
Q. You don't pretend now, in our statement, to give the language?
A. No. I have not heard any of the evidence at all that was before
the committee, except sitting here for a few minutes.
Q. You are a member of the National Guard?
A. Yes, sir.
Q. What regiment?
A. Assistant Adjutant General of the State.
Q. Had you been at Pittsburgh during the riot—the entire progress of
it?
A. Yes, sir.
Q. Were you with General Latta?
A. I was with him most of the time that he was there. On that
morning I had started out when I heard that the troops were out of
the round-house. I went out as far as the arsenal, and when I got
there I found that they had gone in another direction. I was afoot,
and, I think, returned to the hotel.
Q. You were at the hotel when the colonel arrived?
A. Yes, sir.
Q. Do you know whether Colonel Norris communicated that fact to
General Latta that you have just related?
A. Yes; he did. General Latta was in the room at the time.
Q. In your presence?
A. Yes, sir.
Q. That is all you know in relation to the conversation that occurred
between them, is it?
A. That is about all, sir; yes, sir.

General James W. Latta re-called:

By Mr. Lindsey:

Q. I would like you to state, general, just what Colonel Norris stated
to you on his return from General Brinton's command?
A. I did detail that, sir, about as fully as I recollect it, describing the
room and situation and surroundings. I will go over it again if you
desire.
Q. I want to ask you one other question. Did you learn on Sunday
that Captain Aull had not reached General Brinton with that order?
A. I did not find it out, sir, until nearly a week afterwards.
Q. When Major Baugh came to the hotel on Sunday, was anything
said to him by you about whether Captain Aull had reached the
command or not?
A. No, sir.
Q. And he did not communicate anything of the kind to you?
A. No, sir.
Q. When you gave the order to Major Baugh, you had no knowledge
whatever of whether Captain Aull had reached General Brinton with
the first order or not?
A. I had not, sir. I supposed he had. I took that for granted.
Captain Aull: Will General Latta add that he gave me no instructions
to report back?
The witness: I did say that in my report.

Major General R. M. Brinton re-called:

By Mr. Lindsey:

Q. I wish you to state, general, whether at any time during your stay
in Pittsburgh any attempt was made by any of the officials of the
Pennsylvania Railroad Company to control your movements, or the
movements of your troops in any way?
A. No, sir; there was no attempts made by any officers of the
Pennsylvania Railroad Company, to my knowledge, to dictate or
interfere in the slightest with the movements of the troops. I
remember at one time, just after the firing occurred at Twenty-eight
street, that General Pearson was in Mr. Pitcairn's office, and Mr.
Cassatt was there, one of the vice presidents of the Pennsylvania
railroad, and I asked permission of General Pearson to clear the
streets, and to follow the crowd to the arsenal, and he, more in his
manner than anything else, appealed to Mr. Cassatt, and Mr. Cassatt
said I have nothing to do with the movements of the troops, I know
nothing about that whatever. I can say that at no time did they
attempt, to my knowledge, to interfere in any way with the
movements of the troops.
Q. Will you state from whom, or by whom, the provisions were
delivered to your troops, on the hill beyond Sharpsburg?
A. After our arrival in Pittsburgh, or previous to our arrival, I
telegraphed to Pittsburgh for provisions, to General Pearson, and he
procured them from the Union depot, that is, a sandwich and a cup
of coffee. After that, we were in the round-house, and I made
repeated appeals——
Q. I speak of the provisions that were brought after you went
beyond Sharpsburg, on the hill, when you were encamped there—
from whom you received, the provisions, that is, who delivered them
to you?
A. I had a note from Mr. Cassatt, about, I should think, ten or eleven
o'clock that night, that is, Sunday night, saying that he had procured
for us a lot of hams and provisions, &c, and had sent them out. I
thought, at the time, that Mr. Cassatt had left Pittsburgh, but I found
that he had not, and he had also sent two parties from Sharpsburg,
merchants there, who said that they had an order from Mr. Cassatt
to give us whatever they had in their stores, and they gave me an
inventory of it, and said it was at my disposal, and that Mr. Cassatt
had given them orders, and that he would be responsible for it, and
I might say the only provisions I did receive from the time we went
to Pittsburgh, until we arrived at Blairsville, came through his
energies.
Q. Who delivered the line from Mr. Cassatt to you?
A. My impression was, or is, it was Mr. Smith—Colonel Smith, I think
—who brought it there that night. There is one point I should like to
correct. I won't detail any of the conversation, further than to allude
to my evidence, which I gave before. You have, with Colonel Norris,
stated that I wanted to cross the river and intrench. That I did not
say, and, moreover, it would have been impossible, because I had
not any means of intrenching—no tools, or anything of the kind. He
said he saw no crowd, at all, following to Sharpsburg, and that we
should have remained there, in his idea. I merely refer to a dispatch
which General Latta sent to the Governor at that time, and which he
must have received information either from Captain Aull or Colonel
Norris, as it was sent by telegram. It was directed to Governor
Hartranft, dated July 22, p. 36, in which he says, among other
things: "The first division, after stiff fighting for about fourteen
hours, have retired to a point near Sharpsburg, pursued vigorously
by a mob, to the high bridge at that point, under a hot fire pretty
nearly all the way, but they effectually checked the attack." Colonel
Norris returned, he said that there was no mob following us
whatever.
Q. Go on, general?
A. In regard to our not stopping in Sharpsburg, and that
ammunition, &c, could reach us, I want to state that we went on a
point of the railroad below Sharpsburg, where we could procure
provisions, and where we were in direct communication by rail with
Pittsburgh, the same railroad which runs through Sharpsburg, and
therefore we lost nothing by not stopping in Sharpsburg. In regard
to receiving the provisions which Colonel Norris promised us if we
would remain there, the provisions never came, except by the hands
of the Pennsylvania Railroad Company. The evidence which Colonel
Norris has given in regard to the situation we were in, &c., of course
is entirely different from what I have already stated, and from what
the officers who were immediately surrounding us when he joined us
said. They being on the spot, it was not hearsay evidence on their
part, but it was what they actually heard, and they have sworn that
they were sufficiently near to hear every word that was passed at
the time, but if it is necessary, I can produce those officers to
corroborate it.
Q. We have had that.
Colonel Norris: I wish to ask Colonel Smith, whether the provisions
were not sent in pursuance of the arrangements made after my
conversation with Mr. Cassatt and Mr. Bennett?

By Mr. Lindsey:
You may state that, Colonel Smith.
Colonel Smith: As has already been stated, Mr. Cassatt and Mr.
Bennett, and others, had a consultation at the Monongahela house,
about noon of Sunday. Mr. Bennett and Mr. Cassatt left the hotel
together, Mr. Cassatt, at least, and I think Mr. Bennett with him,
went to Allegheny, to arrange with bakers, and other people there,
to prepare sandwiches and other provisions to send out. I left the
Monongahela house about three o'clock, and had this understanding
with Mr. Cassatt, who was to take the road on the north side of the
river, with the wagons of provisions. I was to move up on the south
side, as stated in my examination in chief. I proceeded by certain
routes across the Allegheny river, and at Aetna, I met Mr. Campbell
Herron, and I stated the necessities of the troops, and asked him
whether he could assist me in procuring provisions for them. I had in
mind the conversation and action taken place at the Monongahela
house, between Mr. Cassatt and others. Mr. Herron said that the
store belonging to their furnace, their property, had some provisions
in it, and he sent for his manager, Mr. Chalfant, and with him I
arranged to load up whatever provisions they had, as soon as it
became dark, and that they should be sent on to the camp of
General Brinton's command. My arrangement with Cassatt, was to
wait at General Brinton's camp until I heard from him—either saw
him or heard from him. After that, I was to proceed to execute the
orders I carried from General Latta, which has already been stated
here to the committee. I waited there until about ten o'clock, when a
man by the name of Bradley, a livery stable keeper—he had charge
of hauling the provisions out there—came into camp, and reported
two wagon loads within a short distance, and in the meantime, Mr.
Chalfant had reported there, that a wagon containing hams, and
some other provisions, which we turned over to the commissary of
General Brinton's command. I believe there is no question about
that, but all these arrangements were made in pursuance of the
understanding arrived at between Mr. Cassatt, and Mr. Bennett and
others, at the instigation of Colonel Norris, after his return from
visiting General Brinton's command in the morning.
At this point the committee adjourned, to meet at the call of the
chairman.

Explanatory Note by the Reporter of the Committee.


Owing to an urgent desire on the part of the committee to have the
testimony—taken in shorthand—transcribed and printed as rapidly as
possible after the order to print was made by the Legislature, a
number of men were put to work on it, each man taking a portion,
irrespective of dates. As fast as transcribed, these portions were
printed. This will explain the mingling of dates. Furthermore and
unfortunately, in the hurry and confusion of such quick work, some
of the copy was mislaid or lost before reaching the printer's hands,
necessitating a re-dictation by myself from the original notes. This
will explain the consequent delay.
SAM'L B. COLLINS, Official Reporter of Legislature.
Philadelphia, September 30, 1878.

F. B. Gowen, sworn:

By Mr. Lindsey:

Q. State your residence and official connection with the Reading


Railroad Company?
A. I reside at Mount Airey, in the city of Philadelphia, and am
president of the Philadelphia and Reading Railroad Company, and
have been so since the spring of 1869.
Q. We wish you to state now whether there was any difficulty on the
Reading railroad during the riots last July; and if so, give us the
circumstances?
A. There was a difficulty at Reading, on the line of the Reading
railroad. We did not originate that, nor was it participated in by any
one then in the employ of the company, so far as we have been able
to ascertain. In other words the riotous attacks on property at
Reading, which culminated in the burning of a large bridge over the
Schuylkill river, in the city of Reading, were not the acts of any one
of the then employés of the company, nor, so far as we have been
able to learn, was there any single man then in the employ of the
company absent from his post at that time, nor was there then any
strike of any kind whatever among any of the then employés of the
company.
Q. Did the road continue to run during the troubles?
A. The road was stopped for one day—absolutely for a little over
twenty-four hours—the main line of the road was stopped—all the
branches were running. The main line was stopped at Reading, by
the tearing up of the track, and also the Lebanon Valley railroad was
stopped for a long time, in consequence of the burning of the
bridge, which took place on the night of the day on which the
disturbance occurred elsewhere in Reading.
Q. Was this destruction of property caused by former employés of
the road?
A. Almost entirely. It was caused by a mob that was composed
principally, I believe, of former employés of the company, or led by
them—organized by them—and, of course, participated in, or
witnessed by a great crowd of people, many of whom may not have
been at all active participants, but merely spectators.
Q. State whether you had reason to believe there would be any
difficulty; and if so, what steps you took to prevent it?
A. Early in the spring of the year, as early as March, at least, we had
reason to believe that the society called the Brotherhood of
Locomotive Engineers was arranging to make some kind of an attack
upon the company, somewhat similar to that one which occurred on
the Boston and Maine railroad and the Central railroad of New
Jersey, and we had also reason to believe that there was then being
organized throughout the country, somewhat under the shadow of,
or in some way connected with the Locomotive Brotherhood,
another society, which was to embrace all the trainmen employed
upon the railroads generally, and we thought that the proper way to
prevent such action having a disastrous effect upon our company
and its property would be to state to those who belonged to this
society that they could no longer remain in our employ; and upon a
demand being made upon us by a committee of the Brotherhood of
Locomotive Engineers for an advance in wages of twenty per cent.,
which we believed to be the preliminary step for testing the question
of power, we notified all the engineers and firemen, who belonged to
the Brotherhood of Engineers, that they could not remain in the
service of the company and be members of that organization at the
same time; but, as we understood, that that organization had a
beneficial fund from which the members derived some benefit, we
proposed to give them a fund of the same kind to which the
company also would be a contributor, as well as themselves, so that
no man, in leaving that Brotherhood of Locomotive Engineers, would
lose the money value of his membership. When we issued this
circular, between three and four hundred men, principally engineers
and firemen, and a few others who left in sympathy with them, left
the service of the company. That was in the month of April. That has
been spoken of as a strike, but it was no strike, because these
people who joined it knew that they could not remain in the service
of the company, and it was different from a strike where persons
simply stop work for the purpose of enforcing a demand for higher
wages. A great number of those persons who left the service of the
company in April, still, I think, remained under the impression that
they could force the company to take them back, and they organized
themselves more closely at Reading, and had a series of meetings at
which they took in a great many others that didn't belong to the
Brotherhood of Locomotive Engineers. They had regular meetings in
some hall there, and maintained a position or attitude of hostility to
the company. Their object being to embarrass the company in the
transaction of its business, so that the company would be forced to
take them back; but as the company didn't take them back, as they
desired, from day to day, and week to week, and month to month,
they became very sore on the subject, and I believe that the riot at
Reading—indeed, although I can only speak from hearsay evidence;
but as I took part as a lawyer in the cases that grew out of it, I
derived a great deal of information as to the reason of it. I believe
that when the news came to Reading of the general outbreak upon
the Baltimore and Ohio railroad at Martinsburg, a number of those
former employés of the company assembled at a hall in one of their
meetings, and determined that they would have to do something of
the kind, such as the burning down of the bridge and the tearing up
of the track, and, resulting from that, this attack was made upon the
company, which I believe was confined entirely to such employés as
had left the service of the company, and among them such followers
or sympathizers as could be got into a crowd on such an occasion;
but I believe that none of the employés of the company had
anything to do with it, or took any part in it.
Q. Prior to the breaking out of the riot, had you filled the places of
all those men who had left your services?
A. Yes; their places were filled within two or three or four days of
the time. Indeed, there was no interruption in the business of the
road resulting from those engineers leaving us in the month of April,
except that we stopped the movement of the coal trade one day so
that all the engineers who remained in our service connected with
the coal trade might be on hand in case we didn't have enough new
ones, so that all the trains we call schedule trains, that is passenger
trains and freight trains, might be moved promptly. The whole thing
was over in two or three days. The places of those who left were
immediately supplied. We promoted a great many firemen
competent to take the places of the engineers. I am sure that within
a week or ten days after they commenced to leave, there was no
longer any vacancy in our service not filled.
Q. Was there any difficulty in finding men?
A. None whatever. It was rather remarkable we had them so quickly,
so rapidly. Of course, anticipating this disturbance, we were quietly
on the lookout for men.
Q. Were the new men you employed experienced engineers?
A. Yes; and it was more remarkable still. Our business is a peculiar
one. It is very much more difficult for an engineer from another road
to take hold of a heavy coal train on a down grade, than to handle a
passenger or a common freight train on an ordinary grade. But there
were very few accidents. There were a few such as might result
from the inexperience of men unaccustomed to that kind of
business; but they were remarkably few. Of course we had to be
very vigilant. The company went to some expense in order to guard
against accident.
Q. Were any of those new men you got men who had been
discharged from other roads?
A. I cannot answer that question positively, for the reason that I
don't know it; but I should judge from the habit or custom of the
company in that respect, that no new man was taken into the
service of the company who didn't bring a certificate of good
character. I am sure no one would have been taken that was
discharged from any cause that affected his ability or knowledge as
an engineer.
Q. Then I understand you to say that you had no difficulty in
securing plenty of engineers?
A. None whatever. You will understand, of course, that while quite a
number of firemen left our service, a great many other firemen in
our service were competent to take an engine, and a number of
those were promoted.
Q. Have you any knowledge of the number of new men employed?
A. I think the entire number of engineers and firemen could not
have been more than about from three hundred to three hundred
and fifty—probably not so many. I think about three hundred or
three hundred and fifty would cover all of those two classes—
engineers and firemen.
Q. What steps were taken by the company to punish the rioters at
Reading?
A. We left that, to some extent, to the civil authorities of Reading. In
connection with them, prosecutions were commenced against a
great number. Two of them who were known to have actually set fire
to the bridge, or participated in the actual burning, who ran away,
were arrested at a distance, and plead guilty.
Q. Were they men who had been in the employ of the company?
A. One of them had been at one time.
Q. In what capacity?
A. I think as a brakeman, and he had left the service of the
company, at the time the locomotive engineers left, and at this
meeting I spoke of as taking place at the hall in Reading, he had
been promised by the Brotherhood of Locomotive Engineers to be
paid so much a month, if he left the service of the company. The
other one had never been in the service of the company—not that I
am aware of.
Q. Do you know what steps were taken by the civil authorities at
Reading to suppress the riot at that time?
A. There was very little done at the time. I think that all disturbance
at Reading could have been prevented, if the sheriff of the county
had shown the slightest amount of pluck or appreciation of his
position. He had full knowledge—in fact, he was informed that it was
to take place, but he did nothing practically, except when it was too
late, to issue a proclamation that amounted to nothing.
Q. Do you know how long before it took place that this information
was communicated to him?
A. Information was communicated to him of the intended rising. He
was told of the facts in the possession of the party informing him,
and an offer was made to him of men to act as a posse comitatus,
about eight or ten o'clock in the morning of the day in which the
trouble culminated. He did nothing until late that afternoon. I am
quite confident that a determined man, armed with the law, in the
position of the sheriff of Berks, at Reading, with twenty men—ten
times which number he could have gotten from the citizens—could
have prevented the whole disturbance.
Q. Do you know whether he made any call for help from the State?
A. I am not aware that he did, nor am I really aware of the means
used to bring the military to Reading, or who first made the call for
them. I know the military were sent there by the orders of some one
in the military department of the State, who had authority upon that
subject, and the disturbance was finally quelled by the action of the
military, which unfortunately led to the killing of several persons.
Q. Had there been any reduction of wages on your road prior to
July?
A. I think there had been no reduction of wages on the road for
months before that. There had been two reductions of wages within
the last few years.
Q. Since 1873—the time of the panic?
A. Yes.
Q. How large?
A. Each, I think, was ten per cent. The engineers on the Reading
railroad have been for a great number of years paid according to the
length of service. We have four grades, the first year the men get
the lowest grade, and after they have been in the service of the
company four years, they get the highest grade. That was due
entirely, not to his knowledge as an engineer, but to his length of
service as an employé in the company. It was understood that the
men's wages should increase with the length of time they remained
with us. When any man left us, and came back, again he had to go
down and come up, as the lowest men.
Q. Did that apply to any other employés but the engineers?
A. It applied to the firemen.
Q. Can you give the wages that the brakemen and firemen and
engineers were getting per day.
A. I cannot give it exactly. I think at the time of this disturbance the
highest grade engineers were paid $2 97 per day. I think the firemen
were getting about $1 50 to $1 60 per day. In the coal trade on the
Reading railroad there were opportunities for engineers, during the
busy seasons, to earn more than six days per week. Since the strike,
or shortly after this trouble occurred, in April, as a mark of our
appreciation of the fidelity of those who remained with us and
resisted the temptation to leave when the Brotherhood of Engineers
left—a good many of them, indeed, were members of the
Brotherhood that stayed with us—we made a new grade of
engineers, which no new men thereafter could enter, except after
five years of service, and we put all the faithful men who remained
with us in that grade, and gave them $3 23. We have also that
system among the conductors of the passenger trains. They are paid
according to length of service, and there is an amount of their pay
kept back from them, and invested for their benefit which increases
with length of time.
Q. What were the wages of the brakemen?
A. I think from $1 50 to $1 60.

By Mr. Larrabee:

Q. Were you at Reading during the riots?


A. I was not there.

By Mr. Means:

Q. Did any of those firemen or engineers who left you at that time,
ever make application to come back?
A. A great many, and it was a very sad thing.
Q. Was there a man by the name of Clarke who made that
application to you personally?
A. I cannot give their names, but a great many have made
application personally.
Q. Didn't you tell him that he had done wrong in being led away by
the Brotherhood?
A. I know of a great many such cases. A great many I knew
expressed a willingness to come back.
Q. And acknowledged to you that they had done wrong, and after
their places had been filled by other parties, wanted to be again in
the employ of the road?
A. A great many—I can hardly give you the number. The point with
the company was this: we had taken on three hundred new men,
and the first duty was to them. And most of those new men are
excellent men. Some of them went to the expense of moving their
families hundreds of miles. Many of the old men have written and
asked to come back, saying that they did wrong, and saying that
they were threatened. Many of them have been very seriously
crippled, by reason of not receiving the pay promised them. I think
that they promised sixty dollars a month to every man who quit the
service of the company.

By Mr. Larrabee:

Q. From what source?


A. The Brotherhood of Locomotive Engineers.

By Mr. Means:

Q. The money didn't come?


A. They got very little. From what I understand from a number of
them, I don't think they got enough to make more than ten dollars a
month—hardly that.
Adjourned, to meet at eight o'clock this evening.

SAME DAY.
Friday, March 22, 1878—8, P.M.
Pursuant to adjournment, the committee re-assembled at eight
o'clock, P.M., and continued the taking of testimony.
Robert M. Brinton, sworn:

By Mr. Lindsey:

Q. Where do you reside?


A. I reside at 1301 South Broad street, Philadelphia.
Q. You are a member of the National Guard of Pennsylvania?
A. Commanding the First Division National Guard of Pennsylvania.
Q. What is your rank?
A. Major General.
Q. State where you were when the news of the troubles at
Pittsburgh, on the Pennsylvania railroad, reached you, and what your
movements were afterwards?
A. I was at my office in Washington avenue about six o'clock in the
afternoon, when I received a note from Mr. Thompson, of the
Pennsylvania railroad, saying that General Latta had telegraphed me
some instructions in regard to the riot at Pittsburgh. I proceeded to
my home, where I found a message asking—from Colonel Scott, of
the Pennsylvania railroad, saying that he had a message asking me
to come to the Pennsylvania railroad office to confer with him. I did
so and found him there. He handed me a message from General
Latta, saying that troops were needed, and wanted to know how
soon I could have a regiment ready to proceed to Pittsburgh. I
suggested to him that if any troops were needed the whole division
should be sent. I afterwards received a communication from General
Latta to put the division under arms and be ready to move at a
moment's notice, to report to General Pearson, at Pittsburgh. I
telegraphed to General Pearson my instructions from General Latta,
and immediately ordered the division to assemble, sending out
officers to notify the different commands. It was summer time, and
a great many of the men were absent. It was nine o'clock before I
received the last message from General Latta, ordering me to report,
and about two o'clock we had some six hundred men at the
Pennsylvania depot.
Q. On what day?
A. In the morning of Saturday. I received the message on Friday
night. I kept up communication with General Pearson, informing him
of the number of men I had, and where I was on the road. We had
no ammunition with the exception of a few rounds that the First
regiment had. At Harrisburg we received some ammunition and two
Gatling guns, which we attached to our train. We went through to
Pittsburgh in eleven hours, arriving there about one o'clock on
Saturday afternoon. There I met General Pearson, who ordered me
to disembark the troops. I reported to him and General Latta in the
Union Depot Hotel. The troops were rested and given coffee and
sandwiches, and I ordered an additional ten rounds of ammunition,
making twenty in all.
Q. Distributed?
A. Yes, among the men. General Pearson ordered me to have the
troops ready to move to Twenty-eighth street. At that time. I told
them in coming up, I had seen the hills covered with people, and I
asked them in the event of their ordering me out, to go out with me,
and look over the ground. I was an entire stranger there, and I
thought they must be misinformed in regard to having cleared the
hill, as they said General Brown's brigade had. I also met Mr. Cassatt
at the depot, and I said in the event of our going down and clearing
the tracks, can you move your trains. He said we can; we have
crews already engaged to take out double-headers. General Pearson
then ordered me down to Twenty-eighth street. I ordered one
brigade to go down Liberty street. General Pearson then told me to
go down the railroad, which I did, dragging the Gatling guns. We
arrived at the crossing near Twenty-eighth street, going through
rows of men, who were hooting and howling at us. Previous to this,
while I was yet in the Union depot, I had been approached by
several parties, who wanted to know if I would fire on poor
workingmen. I didn't give any decided answer, not desiring any
conversation with them. I called the brigade companies and several
of the regimental companies together, and told them no matter what
was done to us—even if they spit in our faces—I didn't want a shot
fired, but if they attempted any personal violence, we had the right
to defend ourselves, and we should do it. That was the order from
which the firing commenced. We got down near to the Twenty-
eighth street crossing. There was a large concourse of people there,
far back as you could see, back on the railroad, and we were
stopped. Sheriff Fife and his posse were ahead of us, and I believe
he attempted to read the riot act, at least I heard him saying
something; but he disappeared, and I didn't see any more of him or
his deputies. General Pearson was with us. We could not force our
way through without using some force, and I asked General Pearson
whether he had any instructions to give. He hesitated a moment,
and then said that the tracks must be cleared. The crowd then had
pressed in between the column of fours, and I ordered the fours put
into lines backward, and face the rear rank, about to push the crowd
back from either side, and form a hollow-square.

By Senator Yutzy:

Q. How did you march?


A. The right in front—the First regiment was in front. The crowd
gave back. We had a little difficulty in getting them back to the line
of the cars. Quite a number of cars were there—the Twenty-eighth
street crossing was blocked. The men standing there had evidently
made up their minds to stay, saying that the railroad company had
nothing to do with it, that they were not occupying anything but
public ground. I then ordered two small companies, but finding them
insufficient, I ordered up another command with arms aport, and
attempted to push the crowd back; but finding it impossible, I gave
orders to charge bayonets, which they did, and I saw one or two
men bayoneted. The crowd at that time commenced firing on us, not
only stones but pistol balls, and the men, acting on the orders
already given to defend themselves, commenced firing—firing a few
shots at first, which gradually went along the whole line. At that
time, I had not over three hundred men. The second brigade had
been left back, to guard the yard where the engines were to start
from.
Q. Give us the position of your men at that time?
A. At that time, the rear rank was faced about. The Washington
Grays and the Weccacoe Legion were in double rank, and were
occupying the space between the two ranks of the First regiment
facing east, trying to force their way back along the railroad from the
Twenty-eighth street crossing, and the First regiment was keeping
the crowd back from the railroad from the hill, and also from the car-
shops.
Q. Had you the front and rear ranks of any companies on each side
of the railroad?
A. Yes.
Q. In open order, one facing to the rear and the other to the front?
A. Yes.
Q. And then a command in front of them in the direction of the
railroad?
A. A command on their flank—the right flank—facing eastward.

By Mr. Means:

Q. On the railroad?
A. Yes. The firing lasted about a minute—not over that, and the
crowd, the moment the firing commenced, or shortly afterwards,
dispersed and went in every direction. I gave the order to cease
firing, and my staff officers had the firing stopped, and the ranks,
which were somewhat broken, were re-formed, and I sent a staff
officer to report to General Pearson. I thought he was on the
ground, because it was not certainly—my opinion is, that in three
minutes after he gave me the order to clear the tracks, the firing
commenced. In the meantime, the Pittsburgh troops on the hill—I
had not discovered them before—quite a number of them threw
down their arms and left. I went up the hill a very short distance,
and I saw what was going on there, and I hunted for General
Pearson; finally, I received a note from him, saying he was at Mr.
Pitcairn's office at the outer depot, and, that if I wished to
communicate with him, to send a staff officer, which I did—Colonel
Wilson—and he came back and said that General Pearson desired to
see me. I turned the command over to General Matthews, and
reported to General Pearson at the office of the Pennsylvania railroad
at the outer depot—Mr. Pitcairn's office. I said to General Pearson at
the time, that I thought we ought to continue to drive the crowd. I
understood that they had gone to the arsenal. Several men came up
to me and said that the crowd had gone to the United States arsenal
to arm themselves, and I thought, when I found that they had gone
away, that they would probably get arms and ammunition, and I
proposed to General Pearson that we should follow the crowd. He
hesitated some time about it, and finally I grew more imperative in
my question, and I said, you must do something, I cannot allow my
men to stand on the track with the crowd pushing around me, and
not be allowed to fire. We will either have to move from there or
attack the crowd. Finally, he said that the Second brigade had been
moved into the round-house and machine shops, because he was
afraid that they would be burned, and then he told me to move my
whole force in, amounting to six hundred men, which I did just at
dusk in the evening. We moved in there. They told me to occupy
one round-house and the machine and upholstery shops and the
lumber-yard, and that General Brown would move into the other
round-house at Twenty-eighth street, and I was not aware he was
not there until I saw the flames. As soon as I went there, the crowd
commenced trying to get into the yard, and I had a guard detailed
and put out, and two of them were shot, one through the arm and
one other through the leg, while on their beats. I then got down the
Gatling guns and prepared to fire them, but thought it would be
courtesy to communicate with General Pearson, and tell him what I
was going to do; which I did, and he prohibited me from doing so.
The crowd were firing pistol balls in at us, and a few rifle balls and a
considerable number of stones. I went to General Pearson, and said,
"I cannot stand it, we must defend ourselves." He said he would go
to the mayor and see him, which would do more good than our
bullets would, as he had a great deal of influence over the elements
predominant then, and said that he did not want to take life
unnecessarily, &c., at the same time we were short of ammunition
and rations, only having twenty rounds, and if we were going to be
in a state of siege, I thought we ought to have a sufficient amount.
General Pearson said he would go and see that we got provisions
and also ammunition, and left, saying he would be back in an hour.
He went through the lumber-yard, and left us. At the same time he
told me to open any dispatches that came for him, and I asked if he
had any new instructions. He said, "I want you to hold the place,"
and after he left I proposed to hold it in the way I thought proper, by
firing into the mob at the gates, which drove them away from there,
so that presently there were only pistol bullets and a few straggling
musket balls. We continued to hold it in that way without receiving
any communications from the other world. I expected General
Pearson back every moment. I didn't want to take it on myself to
move out there, or do anything. About two o'clock in the morning
Colonel Snowden, of the Third regiment, called into the round-
house, and directed my attention to what he considered a piece of
artillery. It was quite dark at the time. We watched it for probably
fifteen minutes, when a cloud cleared away, and we decided it was a
piece of artillery, around which were quite a number of men who
were training the piece. I immediately ordered Colonel Snowden to
get fifty men out, and told him to lower their pieces and fire low,
and I gave the order. They had got the piece finally into a position to
suit themselves, and a man had hold of the lanyard. I gave the order
to fire, and when the smoke cleared away eleven of them were lying
there.

By Mr. Lindsey:

Q. The mob had it?


A. Yes; it was a brass field-piece that they had captured from
Hutchinson's battery, I believe. During the whole night we had a
skirmish with those people. They ran cars down loaded with oil, and
attempted to set fire to the building, but fortunately some jumped
the track and blocked the others. The next morning they ran down
cars from the Allegheny side, which came down with their own
gravity, but we finally threw a pile of car wheels on the track, and
upset the cars. They were burning. They were loaded with whisky,
or the most of them with high wines. We put out those fires by fire
extinguishers, and also by a hose that we had there. We finally
discovered that the building part of the Sixth division was on fire,
and it communicated with the building we were in by the oil sheds.
They got on fire, and the building we were in got on fire. During the
night I had communication with General Latta, finding General
Pearson did not return, and told him my situation, and received
orders from him—or suggestions they were afterwards styled—in the
first place to hold on vigorously, but in case I was obliged to leave
there, to go out Penn avenue east towards Torrens station, and that
there would be reinforcements sent to us not later than six o'clock in
the morning; that part of the command—three hundred—who had
failed to join, were at Walls station, and would join Colonel Guthrie
at Torrens, and that they would join us. We waited until ten minutes
of eight o'clock, when the smoke got so great that the men could
scarcely breathe, and we went through the machine shops. We
couldn't go out of the gate, the regular gate, on account of the cars
that had been upset there and were burning, and I went out, I
think, Twenty-third street—I am not very familiar with the streets—
with the intention not to leave Pittsburgh, but to go to the United
States arsenal, where I certainly could get ammunition and possibly
something to eat, as we had nothing but a sandwich and a cup of
coffee since leaving Philadelphia, and through the excitement and
the loss of two nights' sleep, the men were very much fatigued and
thoroughly worn out. We went out towards the arsenal, and
probably had gone a quarter of a mile out Penn avenue, when we
were attacked. I was at the head of the column, and didn't see the
force that was attacking us, but I sent a staff officer immediately to
the rear. The firing was all at the rear, and I think four men were
killed and some ten or twelve wounded.
Q. On your retreat from the round-house?
A. Yes; these men were shot from street cars, and from out of
houses, and from behind chimneys. There was not any regular
organized body, or a body sufficiently large to attack, until we got
nearly to the arsenal, when—the Gatling guns I had placed between
the two brigades, so that we could use them either in rear or at the
front—when we opened with one of them, and dispersed the mob.
We got to the arsenal, and I went ahead to see the commandant
there, and went inside the gate, and went to his house and saw him,
and told him who I was, and that my men were thoroughly worn
out, and asked permission to form in the yard. The men were very
thirsty, and the grounds were shady, and I thought we would wait
there until I had orders from General Pearson. But we received
positive orders from the commandant that we could not come in. I
did not want any altercation with him, so I proceeded on eastward. I
had received a communication from General Latta during the night,
saying that he had made every attempt to feed us, and that it had
been impossible, and I therefore thought that the best thing to do
was to get something to eat. We had arrived within a short distance
of Sharpsburg, when they told us if we came over there we could be
fed. I concluded to do so, and went over there, and just as we got
into the town, we were informed that two of the Fourteenth
regiment, who had been on the hill, had been wounded seriously
there by our shots, and that the people had no friendly feeling for
us, and then I concluded we had better go on and wait for
provisions, which I proceeded to do, when we were met by two
gentlemen, who joined us, one belonging to the Pennsylvania
railroad, I believe, who said we could be fed a little lower down, at
Claremont, where they gave us coffee and rations; but the rations
they brought were berries—not very suitable things for soldiers to
eat. We proceeded to Claremont, and there, awaited orders.
Q. Claremont hospital or the work-house?
A. They are both together—that is the work-house or home they call
it—it is the poor-house. We were fed, I presume, from both houses
—they both sent us out provisions. It has been said that we were
ordered to Torrens, and disobeyed orders in not going there; but the
orders I received, in regard to Torrens, came just one week after the
orders were sent. I got them one week afterwards from Colonel
Guthrie, who handed them to me. Colonel Norris is reported to have
given us some orders, which I positively deny. I never received them
in any way, shape, or form. On the contrary Major Baugh, whom I
left at the Union depot, with General Latta, reported to me out
there. I asked him "have you any orders," and he said "no; I have
not." I said then you will have to go right back to Pittsburgh, and get
me some orders.
Q. Who was it?
A. Major Baugh.
Q. What time did he leave General Latta?
A. I cannot say; but he joined me about two o'clock—two and a half
o'clock.
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!

ebookname.com

You might also like