100% found this document useful (6 votes)
96 views

Instant Download Java Network Programming Fourth Edition Harold Elliotte PDF All Chapters

Fourth

Uploaded by

oeschrezek8c
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
96 views

Instant Download Java Network Programming Fourth Edition Harold Elliotte PDF All Chapters

Fourth

Uploaded by

oeschrezek8c
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Java Network Programming Fourth Edition Harold


Elliotte

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

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Learning Network Programming with Java 1st Edition Reese


Richard M

https://textbookfull.com/product/learning-network-programming-with-
java-1st-edition-reese-richard-m/

textboxfull.com

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/
textboxfull.com

Java Programming Joyce Farrell

https://textbookfull.com/product/java-programming-joyce-farrell/

textboxfull.com

Java Programming Joyce Farrell

https://textbookfull.com/product/java-programming-joyce-farrell-2/

textboxfull.com
Java pocket guide Fourth Edition Robert Liguori

https://textbookfull.com/product/java-pocket-guide-fourth-edition-
robert-liguori/

textboxfull.com

Programming in Java Sachin Malhotra

https://textbookfull.com/product/programming-in-java-sachin-malhotra/

textboxfull.com

Python Network Programming Cookbook Kathiravelu

https://textbookfull.com/product/python-network-programming-cookbook-
kathiravelu/

textboxfull.com

CompTIA Network Review Guide Fourth Edition. Edition Craig


Zacker

https://textbookfull.com/product/comptia-network-review-guide-fourth-
edition-edition-craig-zacker/

textboxfull.com

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/

textboxfull.com
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
One of the biggest secrets about Java is that it makes writing network programs easy. In
fact, it is far easier to write network programs in Java than in almost any other language.
This book shows you dozens of complete programs that take advantage of the Internet.
Some are simple textbook examples, while others are completely functional applica‐
tions. One thing you’ll notice in the fully functional applications is just how little code
is devoted to networking. Even in network-intensive programs like web servers and
clients, almost all the code handles data manipulation or the user interface. The part of
the program that deals with the network is almost always the shortest and simplest. In
brief, it is easy for Java applications to send and receive data across the Internet.
This chapter covers the background networking concepts you need to understand be‐
fore writing networked programs in Java (or, for that matter, in any language). Moving
from the most general to the most specific, it explains what you need to know about
networks in general, IP and TCP/IP-based networks in particular, and the Internet. This
chapter doesn’t try to teach you how to wire a network or configure a router, but you
will learn what you need to know to write applications that communicate across the
Internet. Topics covered in this chapter include the nature of networks; the TCP/IP layer
model; the IP, TCP, and UDP protocols; firewalls and proxy servers; the Internet; and
the Internet standardization process. Experienced network gurus may safely skip this
chapter, and move on to the next chapter where you begin developing the tools needed
to write your own network programs in Java.

Networks
A network is a collection of computers and other devices that can send data to and
receive data from one another, more or less in real time. A network is often connected
by wires, and the bits of data are turned into electromagnetic waves that move through
the wires. However, wireless networks transmit data using radio waves; and most long-
distance transmissions are now carried over fiber-optic cables that send light waves
through glass filaments. There’s nothing sacred about any particular physical medium
for the transmission of data. Theoretically, data could be transmitted by coal-powered
computers that send smoke signals to one another. The response time (and environ‐
mental impact) of such a network would be rather poor.
Each machine on a network is called a node. Most nodes are computers, but printers,
routers, bridges, gateways, dumb terminals, and Coca-Cola™ machines can also be no‐
des. You might use Java to interface with a Coke machine, but otherwise you’ll mostly
talk to other computers. Nodes that are fully functional computers are also called
hosts. I will use the word node to refer to any device on the network, and the word host
to refer to a node that is a general-purpose computer.
Every network node has an address, a sequence of bytes that uniquely identifies it. You
can think of this group of bytes as a number, but in general the number of bytes in an
address or the ordering of those bytes (big endian or little endian) is not guaranteed to

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,
a particular name normally refers to exactly one address. However, names are not locked
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
important advantage of breaking data into individually addressed packets is that packets
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, when you make a local telephone call within the same exchange on a traditional
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:
‘Have you ever done anything which would be likely to give these
people a hold on you? You can be perfectly frank with me, you
know; we lawyers hear a great many curious things, but we never
talk about them. Few men can say that their lives will bear very
close inspection.’
‘I declare to you solemnly that I can reproach myself with nothing
which, if known, would produce the consequences with which I am
threatened. But you know persistent slander is sure to make its mark
sooner or later; it is impossible to say what harm may have been
done already.’
‘Who are the people?’
‘I don’t know.’ Before giving this unexpected answer, Willoughby
looked down on the floor and round the room with the same lost
and puzzled air as before.
‘You don’t know who they are!’ said Mr Blackford with incredulity.
‘That’s rather strange, isn’t it?—Come, Mr Willoughby; we are quite
alone. Who are they?’
‘I can’t tell you,’ repeated the client; ‘I wish I could.’ He looked at the
lawyer with a pitiably anxious expression, and beads of perspiration
began to appear on his forehead.
‘When and where do they attack you?’
‘Incessantly and everywhere. I am never safe from them. Principally
at my lodgings, and after I am in bed at night. They keep me awake
with their outcry.’
Mr Blackford began to be puzzled. His new acquaintance continued
to regard him with the same eager and helpless look, and wiped his
forehead with a tremulous hand.
‘But—but—bless me,’ said the lawyer, ‘if they come and annoy you in
your lodgings, why don’t you give them in charge?—How many are
there of them?’
Willoughby shook his head gloomily. ‘They are too cunning for that,’
he answered. ‘They are careful to keep out of my sight. I never set
eyes on them; I only hear their voices. And they are in hundreds—in
thousands, for all I can tell.’
Mr Blackford of course at once understood the true state of the case,
and the discovery was not a pleasant one. He was by no means a
nervous man, yet he experienced an electrical sensation in the scalp
of his head at the idea that he was sitting within a yard of an athletic
madman. Clearly, it would not do to contradict so opinionated a
person as this was likely to be; he must be humoured, and induced,
if possible, to go away quietly.
‘That’s awkward—very awkward,’ said the solicitor in a reflective
tone. ‘If we can’t see them, you know, how can we get at them so
as to set the law in motion?’
‘I can’t tell what to do,’ said the other despondently; ‘that is why I
have come to consult you. All I know is that they continue to
denounce and threaten me night and day, and that it cannot go on
without being noticed. In that case, my character will be materially
injured, and they will have attained their object. Besides, they are
killing me, Mr Blackford. A man can’t exist without sleep, and I have
had but little for weeks past. And now I learn that they are
contriving a plan to relieve one another at night, so as to keep me
awake.’
There was something inexpressibly grim in the earnest yet matter-
of-fact way in which these impossibilities were related; with
agitation, indeed, but with nothing in the nature of abnormal
excitement or maniacal frenzy. He spoke as a man who found great
matter for trouble, but none for astonishment, in the nightly
irruption into his lodgings of hundreds or thousands of abusive
persons, whose numbers were no hindrance to their remaining
effectually concealed in the space of two small rooms. But he
surveyed the walls and floor at more frequent intervals in his dazed
manner, as though he suddenly found himself in a strange place,
while his moist and shaking hands nervously and convulsively
worked his handkerchief into a compact ball.
Actuated at first by the best motives, Mr Blackford began to question
him cautiously as to his connections and private affairs. It seemed
that, with the exception of some distant relatives at the Cape, he
was alone in the world; nor did he appear to have any friends in
England upon whom he could rely. Having elicited the further fact
that he had an income of five hundred pounds a year, derived from
funded property, the solicitor ceased his questions and delivered
himself up to reflection, while his client anxiously awaited the voice
of the oracle.
There are many members of the junior branch of the legal
profession who are of unbending uprightness and fastidious honour;
there are a few downright knaves; and there are others who stand
neither on the upper nor on the lower rungs of the moral ladder, but
occupy a position somewhere about the middle. These last are
equally prepared to be honest should honesty be made easy for
them, or rogues in the face of difficulty or temptation; and among
their number was Mr Blackford. He was not altogether favourably
known to his brother practitioners; but neither could any definite
charge be brought against him. He had done things which were
certainly worthy of condemnation; but he had hitherto kept clear of
any offence which would endanger his position on the rolls. He
dressed neatly, he had a good manner and a correct accent, and he
did not drink. His business was small, and not of a high class, lying
mostly among the smaller sort of tradesmen; yet he had a certain
connection, and even a few clients of means and fair position; and
he was said to understand his work. He was quite without capital,
and lived a hand-to-mouth life; and he had certain extravagant
tastes of the lower kind. Money was always scarce with him, and he
was prepared to acquire it in any way which offered, so that it was
unattended with risk; for he was quite unburdened with scruples,
considering all profit fair which could be safely gained. And he
thought that in this case he saw a chance of such profit. Willoughby
had answered all his questions, some of them bordering on
impertinence, in the most open and unreserved fashion; he was
evidently disposed to place the fullest confidence in his legal adviser,
looking to him for sympathy and deliverance. Mr Blackford felt more
at his ease in thus parleying with a probably dangerous lunatic, than
a few minutes before he would have thought possible.
The upshot of his meditations was that he concluded to abandon, at
all events for the present, his first very proper and humane purpose
of communicating with the police, and trying to induce them to deal
with the case as that of a lunatic at large, so that the poor fellow
might be properly cared for until his friends could be communicated
with. For this he substituted a different plan of action with admirable
readiness, and with an entire absence of pity or compunction. It was
clear that there was money to be made out of the man by judicious
handling; and Mr Blackford was of opinion that no one could be
better qualified to make it, or more deserving of it when made, than
himself.
He accordingly advised that the threats and accusations should for
the present be treated with contempt. No doubt they were made for
the purpose of extorting money; any sign that they were producing
an effect would only cause the annoyance to be redoubled. In the
meantime he, Blackford, would use his wide experience and not
inconsiderable abilities in his client’s behalf, and had no doubt of the
ultimate success of his endeavours to discover the offenders and
bring them to justice. The poor madman, with tears in his eyes,
thanked him for his kindness and attention, declared that a load had
been lifted from his mind, and was about to withdraw, when the
solicitor stopped him with an air of having suddenly recollected
something.
‘By the way,’ said he, ‘it’s hardly worth mentioning—but cases of this
nature involve considerable expense to begin with, in the way of
inquiries and so forth. It is generally the custom—— Well, to put it
plainly, I think I must ask you for a small present payment on
account; say five pounds or so.’
‘Of course, of course—certainly,’ said the other, fumbling nervously in
his pocket. ‘I am much obliged to you for mentioning it; this is my
first experience of the kind, I am happy to say. I have not quite the
sum you mention with me at this moment. Would three pounds ten
be enough for the present? and I will send the rest by post.’
‘O yes, that will do very well; only a matter of form, you know,’ said
the solicitor carelessly, but laying an eager grasp upon the coins. ‘I
hope to write to you satisfactorily before long—till then, good-bye.’
So soon as his new client had left, Mr Blackford assumed his coat
and hat and went off to keep his appointment with Mr Franklin, who
lived in Camden Town with his married niece and her husband. As
the solicitor strode rapidly along, he felt a different being from the
man who, but a short half-hour before, had been reading his letters
in so despondent a mood. The sudden and unwanted accession of
business from two quarters at once on the same day gave him a
feeling of importance; and the consciousness of the four unexpected
gold coins in his pocket thrilled through him with a comforting glow,
like that of a glass of old ale on a frosty day. Willoughby, if properly
managed, might prove a small gold mine before his madness should
develop itself to an extent incompatible with attention to legal
matters; and visions arose before him of a possible inquiry de
lunatico, with its expensive accompaniments of the appointment of a
‘committee’ and the administration of a nice little estate; all to be
conducted, in the not distant future, to his great pecuniary profit, by
that trustworthy and able man of law, James Blackford. His castle-
building extended to an important family connection thence to arise;
to the hiring of more commodious offices in a better situation,
necessitated by a rapidly increasing business; and by the time that
he found himself at the end of his walk, the unpaid rent and the
uncompromised compensation action had faded in a glow of
splendid possibilities.
Mr William Franklin was a tall and gaunt old man, with a red face, on
which dwelt continually a savage and sardonic smile, framed in a
bristling fringe of silvery-white hair. His character might almost be
summed up in the expressive phrase of certain of his acquaintance—
friends he had none—by whom it was predicated of him that he was
‘an ugly customer.’ He was, in fact, an evil-tempered and malicious
bully, whose selfish and tyrannical disposition had been fostered by
an undue consciousness of the twenty-five thousand pounds which
he had made in business, and by the assiduous court which his
wealth caused to be paid to him by expectant relatives, with all of
whom he took pleasure in quarrelling in turn, enjoying with a
fiendish glee their subsequent agonies of self-abasement.
‘So, it’s you at last!’ said this amiable old gentleman, when Mr
Blackford was shown into his presence. ‘Thought you were never
coming. What’s kept you?’
The solicitor, with great humility of manner, apologised for the
unavoidable delay, and alluded to the overwhelming pressure of
business and the constant calls upon his time.
‘Oh, I’m sure—I’m sorry to have put you about so,’ said Mr Franklin
with vast politeness. ‘I couldn’t think of detaining you when you’re
so busy. It’s a matter of no consequence, after all. Pray, don’t wait;
I’ll send to Jones and Crowder; I daresay they won’t be too much
engaged to come at once.’
Greatly alarmed, Mr Blackford hastened to protest that his time was
entirely at Mr Franklin’s disposal.
‘Then don’t tell me a pack of lies!’ roared the client with an
instantaneous change of manner, facing round from the fireplace,
poker in hand, with every apparent intention of committing a violent
assault upon his solicitor. ‘Man alive! don’t I know that it’s just as
much as you can do to keep body and soul together in that poky
little hole of an office of yours?—Business, indeed! As if I wasn’t
about the only decent client you have! And why I am your client,
goodness only knows. It’s compassion, I suppose. I always was too
soft-hearted for this world.’
His visitor could have furnished him with a better reason—namely,
that no other lawyer had ever been found capable of putting up with
his insolence and tyranny. But Mr Blackford had plenty of self-
control, and could bear a good deal where anything was to be got by
doing so.
The soft-hearted gentleman smote the coals violently, fulminating
subdued anathemas the while with a dreadful grin. The solicitor,
knowing his man, remained perfectly quiet; and presently Mr
Franklin spoke again, abruptly, but in a quieter tone.
‘Here! I want to make my will. I’m going to do it at last—in a fashion
that will astonish some of ’em. They’ve been anxious enough about
it these ten years and more. I hope it’ll please ’em when it’s done. A
set of hungry hounds! Ready to lick the dirt off my boots for the
money, and nothing too bad to say of me behind my back. I know it
as well as if I heard it. Not a penny—not a penny for one of ’em! I’d
rather take it into my grave with me—not but what they’d grub me
up again, if I was in the middle of the earth.’
There was again a short silence. Mr Blackford awaited his
instructions.
‘Then there’s this young Tom Wedlake been giving me his sauce, just
because I spoke a word to that lazy young baggage of a wife of his
—said he wasn’t going to stand it—he wasn’t going to stand it—the
beggar! and if I didn’t like it, I could go. Will I! I’ll stay here, just to
spite him. Besides, I’m a deal too comfortable to move. She won’t let
him turn me out—the artful minx. “Dear uncle—don’t be cross with
me, dear uncle!”’ said Mr Franklin with an access of fury, and a
ludicrous assumption of a feminine falsetto. “Leave all your money to
your niece, dear uncle; that’s what you’ve got to do.” Not a brass
farthing, by Jove! He doesn’t want my money, doesn’t he? and he
has the impudence to tell me so! Very good, Mr Thomas Wedlake;
I’ll take you at your word. I’ll pay you out, you—you—rapscallion!’
The furious monologue seemed to have spun itself out; so Mr
Blackford ventured a word.
‘Then I gather, sir, that you do not intend to leave any portion of
your property to your nephew and niece—and I have no doubt you
are exercising a sound discretion, as always. But as you are justly
offended with your other relations, what disposition do you think of
making?’
‘Mind your own business!’ was the unexpected retort.
Mr Blackford felt rather aggrieved, as the matter was clearly his
business; but he said nothing. The old man continued his jerky
discourse, addressed more to himself than to his visitor.
‘You’re right, though.—What shall I do with it? I’ve been asking
myself the same question ever since I wrote to you last night; and
now you’re here, I’m no nearer the answer. It’s a deal of money,
hard got, and soon spent; and I don’t know who it’s to go to. Plaguy
hard to leave it at all. No good grumbling about that, though. I won’t
give it to an hospital, or build a church, or endow almshouses; I’ve
no patience with that sort of humbug. As if a man hadn’t been
robbed enough all these years, what with rates and what with taxes.
I can’t keep the money myself, and there’s no one to give it to—no
one.’
Perhaps, through that heart, all seared and scorched with evil
passions, eaten through and through with corroding suspicion, there
darted a momentary pang at the thought that there was not a
human being from whom the gift of all his painfully acquired wealth
would buy one tear of sorrow, or even one grateful remembrance of
the giver.
He sat brooding with a gloomy brow; and this time the silence was
so long that Mr Blackford was about to break it at the risk of another
rebuke, when Mr Franklin smote his hand upon his thigh and
laughed—a harsh and cackling laugh, devoid of mirth or geniality.
‘Blackford,’ said he, ‘I’ll leave it to you!’
Had the lawyer received a blow from the ready poker which stood in
the nearest corner of the fireplace, he could hardly have been more
thoroughly stunned. ‘To me!’ he managed to gasp out, after a
moment’s astounded silence.
‘I’ll leave it to you!’ repeated Mr Franklin, nodding emphatically. ‘Ain’t
you willing, that you stare like a stuck pig? It’s not because of any
regard for you—don’t think it. I’ll leave it to you, just because it will
be about the worst kind of sell for ’em all I could anyhow invent. I
hate ’em—every one! and the thought of their faces when they come
to hear the will read, will be about the only consolation I shall have
for being obliged to part with it at all. And mind you, I shall make it
a condition that they do hear it read. You are to call them all
together for the purpose, and you’re not to breathe a word
beforehand of the nice little surprise in store for ’em. Every man-Jack
will think he’s been “remembered”—and so he has, I assure you!
You’ll have a nice time of it with ’em, Blackford. D’ye quail at the
thought of it—eh? If so, say the word, and we’ll think of something
else.’
‘Not on my account, I beg,’ said the solicitor, recovering his senses. ‘I
daresay I shall be equal to the occasion. But Mr Franklin, my dear
sir, how am I to thank you for such munifi’——
‘You’d better not thank me at all, if you’re wise,’ said the eccentric
testator; ‘you may sicken me like the rest, and then I shall alter my
mind. Bosh! I know you well enough. You’ll try to double the money
as soon as you get it; and you’ll either lose it all and hang yourself,
or you’ll get mixed up in some piece of rascality that will bring you to
penal servitude. You have my instructions. Go and make the will;
and bring it here to-morrow, and I’ll sign it. And look here! bring two
witnesses with you; I don’t want any one in this house to know what
I’ve been about. Here’s a list of the securities. Be off! Good-bye—get
out!’ And with this unceremonious dismissal, the interview came to
an end.
As he hurried back to his office, Mr Blackford was able at last to
realise the immensity of the good luck which had befallen him in this
extraordinary manner. Twenty-five thousand pounds, all invested in
sound Stock Exchange securities! Good-bye to the strife for bread;
to the trap-net of petty pecuniary embarrassments which meets and
deadens effort at every struggle; to the haunting care which makes
hard the nightly pillow and drives away slumber before the dawn; to
the hand-to-mouth existence, and the thousand-and-one daily
degradations of a struggling professional man. Good-bye to one and
all—if Mr Franklin’s suddenly conceived purpose would but hold until
he should in good time, the best of time, betake himself to a region
where codicils are an impossibility. But one thought was present to
the lawyer’s mind at that moment—to get the will drawn and signed
with all possible expedition; but one hope was his—that his client
might thereafter make an edifying end with as little delay as
possible.
AVALANCHES.
The word avalanche carries with it a sound of terror and dismay,
which may well appal any mind. Happily, avalanches are unknown in
Great Britain; but in Switzerland they are sadly too frequent. They
are known also under other names in some parts of Italy and
Germany. Avalanches consist of large accumulations of snow, set
free by some means, descending from an elevated region to the
valley. Their action is more or less twofold: chiefly by the mass of
the snow sweeping away or overwhelming everything which comes
in its course; but also, sometimes, by so violently disturbing the air
as to cause a hurricane, which in its destructive force kills men and
cattle, and tears up trees and even houses from their solid
foundations.
Avalanches have been divided into four classes. There are powdery
avalanches, in which the snow and ice break up into powder, forming
a kind of silver cloud, sparkling like quicksilver, and making a noise
like distant thunder. This kind is more dangerous by reason of the
commotion produced in the air, than by its weight or power to
overwhelm. There are what are called creeping avalanches. The
mass of snow, being disengaged, moves down a more gentle slope,
as on an inclined plane, and so is sluggish in its course. Then there
is the glacier avalanche, which consists of a large mass of ice
detached from the glacier above, which descends to the valley. This
is the least dangerous kind, and is more common in summer. Lastly,
there is the avalanche proper, which is the most dangerous of all,
and consists of vast accumulations of snow set free from above,
which increase in force as they descend, overthrowing houses,
tearing up trees, burying villages, and swallowing up forests, cattle,
and human beings. Sometimes, however, an avalanche may change
its character in its descent; as, for instance, a creeping avalanche
may reach a steep declivity, and the mass of snow falling on the
sharp angles of a rock, it may be shattered, and its mass dispersed
in a cloud of powdery snow. Cases occur sometimes in which,
instead of burying the objects with which they come in contact, they
drive them into the valley, and deposit them at a considerable
distance from their original position. A remarkable case of this kind
occurred in 1806; an avalanche which fell in the Val Calanca,
transferred an entire forest to the other side of the valley, and
planted a fir-tree on the roof of the rector’s house!
An instance may be given of the effects of a powdery avalanche
which occurred in the Oberland, in the canton of Berne. It was on
the 12th of December 1808, about six o’clock, that the avalanche
descended on the village of Shärmatt, sweeping away three houses,
and carrying one of them fully three hundred yards, and some
portions of it more than half a mile. In one house two persons were
smothered by the snow, and five in the other. The third house
contained six children and their uncle. Some of the children were in
bed, and the rest were sitting at a table learning their catechism. All
at once the light was put out, a thick darkness surrounded them,
they felt themselves enveloped in snow, and whirled along they
knew not whither. Presently a deep ditch stopped the progress of the
house. The uncle, soon recovering his presence of mind, began to
grope about the snow for the children. After a long search, he found
them—all alive, and not seriously injured. He took them to a barn
near by, where they were obliged to spend the remainder of the
night, some of them almost naked, though the cold was intense. The
father of the children was engaged with his cows at a shed at some
distance, and was horror-struck, when he returned to where his
house had stood, to find it gone—swallowed up, as he supposed,
with the whole of his family. But his fears were soon exchanged for
joy; and the sight of the meeting of the father and his children and
brother affected the roughest of the bystanders to tears.
On the same evening, a second avalanche fell, and was fatal to the
inhabitants of another house. The only living thing which survived
was a little dog which had taken refuge in the cellar. As soon as the
ruins of the house were removed, he jumped out of his hiding-place,
barking at the workmen.
In this case was an instance of the hurricane produced by the
agitation of the air by means of the descending cloud of powdery
snow. Several cattle-houses, with the cattle, were torn from the
ground and driven like chaff before the wind. There was also
another instance of the wonderful power of the hurricane in the case
of a barn full of hay, which was carried more than a quarter of a
mile, and deposited on the opposite side of the river in its right
position, with its contents uninjured!
It has sometimes happened that the snow has not fallen to a
sufficient thickness to crush the houses, in which event the inmates
have more chance of being saved, as the porous character of the
powdered snow allows of sufficient air to sustain respiration. This
was the case when, in 1749, the entire village of Tauetsch, in the
Grisons, was one night overwhelmed by a powdery avalanche, which
descended so noiselessly that the inhabitants were not aware of the
calamity, and wondered in the morning why the day did not break.
One hundred persons were covered in by the snow in their houses,
sixty of whom were got out unhurt.
But perhaps the most remarkable instance of imprisonment in the
snow of a descending avalanche occurred in the hamlet of
Bergoletto, in the valley of the Upper Stura, at the foot of the Alps,
near the fortress of Demonte, in Piedmont. Three persons survived
an incarceration of five weeks. It was in the winter of 1755, when
the falls of snow had been so very heavy that there was danger that
its weight would break through the roofs of the houses. On the 19th
of March, therefore, some of the people tried to avoid the danger by
removing the snow from their house-tops. Among those so engaged
were a man named Roccia, and his son, a lad of fifteen. The village
clergyman was at this time leaving his house for his church, when he
saw two avalanches descending. Calling to Roccia and his son, he
returned speedily to his own dwelling. Father and son instantly fled
towards the church. They had not run more than forty yards when
the lad fell close behind his father, who, turning round to assist his
son, was seized with horror on seeing that his own house and the
houses of his neighbours were buried beneath an enormous pile of
snow. His earthly all was swallowed up—his wife, his sister, his
children, gone! The shock overcame him, and he fainted. His son
soon recovered himself, and helped his father to the house of a
friend; but he was five days before he was sufficiently restored to
make any exertions in seeking his lost ones. Thirty houses were
destroyed, and twenty-two persons were missing, among them the
clergyman who gave the alarm. The snow lay over the village to a
depth of more than forty feet, and extended its destruction some
ninety yards in length by twenty broad.
The news of the disaster brought more than three hundred men
from the neighbouring valleys. With iron rods, they sought to
discover where the houses were; and then they commenced digging
vigorously; but the depth of snow was so great (another heavy fall
coming on) that they could make little or no progress, and were
compelled to desist, after toiling for several days. No hope could
they entertain of any one being preserved alive; and as the warm
winds were expected to set in in less than a month, they resolved to
wait until the mass should be partly melted.
On the 18th of April the men returned to their sad task. Roccia was
among the most active of the workers. Though he had no hope that
he should ever see any of his dear family alive, yet he laboured
diligently, assisted by his son and a brother-in-law. After six days
they advanced so far, that by breaking through two yards of ice they
could touch the ground with a long pole. On the following day they
were joined by another brother of his wife, who had been led to
come and assist by a dream which he had, in which he saw his sister
alive, begging of him to help her. Setting to work with new vigour,
the four rescuers made their way into Roccia’s house—but it was
silent and tenantless. Thinking that those they sought might have
taken refuge in a stable which stood in a sheltered position some
thirty yards from the house, they renewed their energies in that
direction. After burrowing through the snow for some time, one of
them thrust a pole through an opening. On withdrawing it, they
heard a faint voice say: ‘Help, dear husband! help, dear brother!’
They now worked away with redoubled industry, and soon made a
considerable opening, through which one of the brothers descended.
The spot was totally dark, and he could see no one. ‘Any one here?’
he cried. His sister answered in trembling and broken accents: ‘It is
I, dear brother. My sister-in-law and my daughter are alive too. I
have always trusted in God that He would send me relief, and He
has been graciously pleased to preserve me and deliver me.’
Her husband and other brother also descended; and there were joy
and tears and thankfulness beyond expression.
The imprisoned women were too weak to move, and were shrunk
almost to skeletons. With great tenderness they were removed to
the house of a friend, where they were put to bed and nursed with
care and affection. The daughter recovered soonest, and the
unmarried woman was able to walk in a week or two; but Roccia’s
wife, who had been in a more cramped position than the rest, was
the last to regain the use of her limbs; and her eyes were ever
afterwards affected with dimness, from being suddenly brought out
of her prison into the light of day.
We give a description of their imprisonment from the lips of Roccia’s
wife. When the dire calamity befell them, she was in the stable with
her sister. They had gone there with some rye-flour gruel for one of
the goats which, on the evening before, had brought forth two dead
kids. Roccia’s daughter and a younger son were with the women,
standing in a corner among the animals, waiting for the sound of the
bell to go to church. In the stable were a donkey, six goats, and half-
a-dozen fowls. Roccia’s wife was about to leave the stable to go to
her own house. Scarcely had she reached the stable door, when she
heard the warning voice of the minister. Looking up, she saw the
descending avalanche, and heard a sound as of another at some
little distance. She hurried back into the stable and told her sister
and her children. In a few minutes the snow descended upon the
building, crashing in the roof and part of the ceiling. To save
themselves they got into the rack and manger, the latter being under
the main posts of the building, and therefore able to bear the
immense pressure. They occupied, however, a very uncomfortable
posture, crouching against the wall in a space only a little more than
a yard in breadth. They had escaped instant death, but the more
painful and lingering death by famine seemed certainly to await
them. They were oppressed with the thought of how they could
subsist under such circumstances. The children did not lose heart;
they said they had had breakfast, and could do very well until the
next morning. The aunt had a few chestnuts in her pocket; and two
each of these served for their supper, with snow-water as a
beverage. In the bakehouse near the stable was the whole produce
of yesterday’s baking. They made repeated attempts to force their
way through the snow to the bakehouse, but all in vain. There was
only one resource left, and that was the goat which had recently
brought forth the two dead kids. This supply proved invaluable. On
the second day they felt the pangs of hunger; they divided the
remaining chestnuts among them, and also a quart of goat’s milk.
The third day they made another effort to get to the bakehouse; but
the weight of snow was too much for them, so they gave up all
hopes of help from that direction. They were therefore shut up to
the milk of the one goat.
To feed the goats was now one great object. Two of them were near
the manger—the one already yielding milk; and the other, being with
young, might be expected soon to do so, if they could only supply
them with food. Over the manger where they lay was a hole into the
hayloft; through this hole they pulled down the fodder into the rack;
and when they could no longer reach it, the sagacious creatures
climbed upon their shoulders and helped themselves.
At the end of the first week, the boy began to sink. He had
complained of great pain in his stomach. His mother nursed him in
her lap for a whole week, when he desired to lie his length in the
manger. His hands and lips were cold, and his respiration feeble. His
mother put a little milk to his lips, but he could not take it; and then
with one tender cry, ‘O my father in the snow! O father, father!’ he
expired.
Throughout the whole of their imprisonment they were in total
darkness. For nearly three weeks the crowing of the cock enabled
them to distinguish night from day; but at the end of this term
chanticleer died, and his companions followed him one by one. They
then literally took ‘no note of time.’ The donkey and the other goats
were very restless for some time, but at length they fell a prey to
hunger and exhaustion. The milk of the first goat gradually
diminished; but the kidding of the second increased the supply, and
as they killed the kid, though with great reluctance, the supply held
out until the day of their deliverance. The poor goat became quite a
solace to them, as it was so tame as to lick their hands and face.
The poor creature was ever afterwards an object of great affection
in the family.
We need only add one or two interesting facts. During their five
weeks’ imprisonment they suffered little uneasiness from hunger
after the first week. The effluvia from the dead animals were far
more disagreeable, as also the vermin which infested the place, and
the great coldness of the snow-water which trickled over them. The
constrained position was also a source of great misery. During the
whole of the time, Mrs Roccia had no sleep; but her daughter and
her sister had intervals of repose equal to their nightly rest. Their
deliverance was a matter of great thankfulness to all concerned; and
many a winter’s evening was spent in relating around their humble
hearth the sufferings, the mercies, and the deliverance of that
eventful time.
A NIGHT IN AN INDIAN HILL-FORT.
Some short time ago, I being then an insignificant member of the
Army Headquarters staff at Simla, the hill-capital of India, it became
desirable to increase the number of hill-stations for the summer
accommodation of British troops. It was thought that the Chor
mountain, the most prominent peak of which is some sixty miles
from Simla, would on its lower ridges afford suitable sites; and
accordingly, a Committee of officers was formed for the purpose of
reconnoitring and making a report. This Committee consisted of a
well-known general, a major of Engineers, and myself, a humble
sub. Somewhat trying work it was to get to the Chor, the road being
of the most breakneck description, and the monsoon rains showing
symptoms of bursting for our especial delectation. However, we
trudged on manfully, climbed to the very topmost peak of the Chor,
which by our aneroid we made over twelve thousand feet, and saw
—nothing; for, by evil chance, one of the most magnificent views in
Asia was barred to us by clouds which shut out everything except
the first mile or two of the hog-backed ridges below us.
Disappointed, we descended; and that night it was arranged we
should separate and return to Simla by different routes, so as to
make the President’s report as comprehensive as possible. In the
execution of this idea, I found myself the next day at a place called
Bhairogh, whence I proceeded—on foot, for we had been obliged to
send our ponies back, owing to the state of the road—to a village
called Tali. Here at first I thought of camping, as I had come some
eleven miles up hill and down dale; but the place was so bare and I
was so anxious to push on, being short of provisions, that I suddenly
determined to double my march and make for a fort called Rajgarh,
and described as being some twelve miles farther on. Unfortunately,
I was dilatory in starting; the march, as usual, was longer than I had
been led to suppose; the road was hilly, and it was not until about
nine p.m. that I found myself peering through the darkness in the
vicinity of my destined camp.
Camp, did I say? It was very soon evident that there was to be no
camp for me that evening, and, what was still more objectionable,
no supper. Slowly as I had walked, my servant with whom was all
my money, and the coolies with my tent and kit, were miles behind.
It was too late for such an unkempt ragamuffin as I undoubtedly
was to disturb the garrison, so I shortly made up my mind to
bivouac peacefully under a tree. Just outside the fort, however, and
close to the spot I had marked out for my resting-place, two natives,
by the light of a fire, were hammering some metal vessel with such
animation as to wholly preclude the possibility of sleep. To these
enthusiasts I explained that I was a sahib, and suggested they
should postpone their operations till next morning. They, naturally
enough perhaps, demurred; and I wrangled, and they continued
their metallic fantasia until I could stand it no longer. Thinking,
perhaps, I could persuade the local head-man to assist me in getting
a night’s rest, I presented myself at the gate of the fort, a square
walled inclosure of no strength, and demanded admittance. After
much palavering with the sleepy sentry, I was let in past the outer
wall, but not into the inner part; whereupon, I asked that the head-
man should be sent for, and further clamoured for a chair. Seated
upon this, and curiously scrutinised by a few promiscuous hill-folk, I
waited for some five minutes, wondering why nobody came. At last
a gate in the inner wall was thrown open, and out poured a
procession, lit with torches, and headed by an evidently high-class
native in flowing white robes. After the interchange of salaams, this
individual, who subsequently turned out to be the tehsildar
(administrator of a district), said to me with much humility: ‘Is your
honour sent by the government to see if troops can be encamped on
our hills?’
I admitted the soft impeachment; whereupon the tehsildar smiled
benignly, and a succession of happy grunts and ‘It is hes,’ ran round
the rest of the assembly, who had grouped themselves in an
admiring circle round my chair.
‘Ah, your honour, we are made very happy by seeing you! The
Deputy Commissioner of Simla wrote to our rajah to say that you
and two other sahibs were coming; but we feared you had gone by
another way.’
This was gratifying, but not to the purpose. I accordingly explained
to my friend my situation, begged him to discourage the metal-
workers, and asked that my servants when they arrived might be
directed to my whereabouts. At this, consternation reigned on every
side, and the tehsildar nearly fainted.
‘Your honour sleep under a tree!’ he gasped. ‘It is not to be thought
of. I have given orders for a banquet to be prepared for your
honour; and your sleeping-room is by this time ready. Will your
honour be pleased to come and see it?’
I followed the obsequious tehsildar, and inspected my proposed
sleeping apartment, a small room, with no outlet but the door, and
literally stuffed with carpets, quilts, and pillows, evidently collected,
hurriedly for the occasion. What pleased me most was the sight of a
bed, which I at once ordered to be brought out into a sort of inner
veranda, not wishing to be wholly suffocated. I then did justice to
the ‘banquet’ as a man who had trudged some five-and-twenty miles
over a difficult country might reasonably be expected to do. The
surroundings were rather oppressive, and the civilities of my host
and his companions rather overwhelming; but I was not in a mood
to be critical, and it was with considerable self-satisfaction I
eventually sought my couch, falling asleep almost simultaneously.
The next morning, I prepared to start on another march, and again I
had an interview with the tehsildar and the rest of the garrison. I
could not help noticing that though the man was perfectly polite and
obliging, there was a change in his demeanour and in that of his
following. No more was my every movement watched with eager
curiosity, no more was my every mouthful accompanied by beaming
smiles and grunts of satisfaction. This did not distress me greatly,
but I thought it curious, and when I had said farewell and had fairly
started on my journey, I asked my servant what it all meant.
The man smiled, and explained: ‘Deputy Commissioner Sahib he
write to rajah this place and say: “Very great general and two other
sahibs coming see your country. Government want put soldiers in
your country when hot time comes. Good for you if government do
this, because government pay you well, and country getting plenty
rich.” Rajah he very pleased, and write to all his tehsildars and say:
“When great general sahib comes, you make plenty show and big
dinner.” Last night you come to fort, and it rather dark; tehsildar he
not see very well, and he think you be very great general. This
morning come, he see you not general, and he plenty sorry such big
dinner make!’
WHAT GOES TO THE MAKING OF A
SILK GOWN.
Visitors to the International Exhibition at Edinburgh who have
watched with wonder and admiration the deft fingers of the silk-
winder as she winds the delicate straw-coloured threads from the
cocoon, may be interested to know something of the rise and
progress of the manufacture of this, the most beautiful and costly of
all our textile fabrics.
The spinning of silk was first discovered in China, and is supposed to
have been practised there almost two thousand eight hundred years
before the birth of Christ. A Chinese empress, See-ling, a native of
India, is said to have discovered, probably by accident, that those
wonderful cocoons which the silkworm prepares for its
transformation might be pressed into the service of man in the same
way as cotton and flax are. She unravelled the delicate fibres, and
found them to be strong, though fine, and capable of being woven
into a web. Prosecuting her researches, she learned how to breed
and rear the worms so as to obtain an abundant supply of cocoons;
and in this way initiated a new industry, which the empresses who
succeeded her delighted to foster.
For a long time the weaving of silk was in the hands of the court
ladies; then, by slow degrees, it passed from rank to rank, until it
became the favourite occupation of all classes of women. It was
introduced into Europe by way of Constantinople; and in 527 a.d., in
the reign of Justinian, it had become so far common that garments
of silk were the favourite wear of the Byzantine nobles. The origin
and manufacture of this beautiful fabric seem, however, to have
been very imperfectly understood, until two monks who had
travelled through India and China astonished the emperor and his
court by informing them that the shining silk garments which they
admired so much owed their existence in the first place to the
labours of a small worm. Justinian, like many crowned heads, was
often in want of money, and it occurred to him, as he listened to the
travellers’ wonderful tales, that if he could introduce the
manufacture of this costly cloth into his dominions, it would be a
sure and increasing source of revenue. Thus judging, he offered the
two monks a large reward if they would procure for him a supply of
the eggs of this wonderful creature. The monks undertook the
commission; and after much difficulty, succeeded in procuring a few
ounces of the eggs of the silkworm moth. This treasure, which they
had not obtained without danger, they hid in two hollow canes which
they used as staffs. One of these precious staffs was lost; but the
other was safely presented to Justinian; and the supply of eggs so
curiously procured laid the foundation of a flourishing silk-
manufacture.
This, which was at first a close monopoly, guarded with the most
jealous care, gradually became extended to other countries, as wave
after wave of conquest swept over the Eastern Empire. One of these
conquerors, Roger, king of Sicily, in 1140 transported a whole colony
of silk-weavers, with a plentiful supply of eggs, from Constantinople
to Palermo, where, for many centuries afterwards, a great
manufacture of silk flourished. It was not until nearly a hundred
years after the Sicilian king’s invasion of Constantinople that the
enterprising citizens of Genoa and Venice succeeded in procuring a
supply of the coveted eggs, and very soon made their countries
famous for the manufacture of silk. In 1300, the velvets of Genoa
were renowned throughout Europe; but there was always an
attempt, more or less, to make the manufacture of silk a monopoly;
and it was not until nearly two hundred years after the Italian cities
had become famous centres of the silk industry, that the
manufacture was introduced into France. When it did come, it was,
as in the case of Roger of Sicily, in the train of a conqueror. Francis
I., while pursuing his conquests in the north of Italy, became aware
of the wealth and importance of this branch of industry, and
succeeded, partly by bribery, partly by force, in planting colonies of
silk-weavers in Lyons, Avignon, and Tours. In all these cities it
flourished greatly in a short time, particularly in Lyons, which
speedily became one of the centres of the silk-manufacture
throughout Europe.
In England, James I. made an effort to introduce it; but, in spite of
his fostering care, it did not at first take kindly to the soil, and, in
fact, never throve until it was re-introduced by the Huguenot
refugees who were driven from France by the revocation of the Edict
of Nantes. Under their care it became for a short time very
prosperous, and England bade fair to rival either Italy or France; but
the trade was from the first a close monopoly, from which all
outsiders, either foreigners or natives, were jealously excluded. The
consequence of this was that there was no improvement; the
manufacture stood still in England, while in France it was making
gigantic strides. It was in vain that successive acts of parliament
were enacted to foster and encourage it; it continued to decline until
1824, when it was at last freed from the swaddling bands which had
so long impeded all free growth and progress. It has, however, been
found impossible to recover as yet our lost ground, and the great
proportion of the silk used in this country still comes from France. In
the year 1877, our import of silk amounted to £12,631,822, of which
by far the greater amount came from France. France, indeed, at this
moment far surpasses, in the production of silk, any other country in
the world, the annual value of this manufacture being about thirty
millions. Many causes have been at work in France to produce this
result, one of which is undoubtedly the attention paid to technical
education, and the extent to which it is taken advantage of by both
men and women.
There are two distinct systems under which, across the Channel, this
important manufacture is carried on. Around Lyons, the trade is in
the hands of small practical manufacturers, who have risen by dint
of industry and skill from the ranks of workmen. These men set up
in business for themselves, but not in any large way; they do not
employ many hands, and often themselves work harder than any of
their assistants. These hands, both male and female—for women are
employed as largely as men—can and do receive instruction at a
very cheap rate, and from the best masters, at one or other of the
Ecoles de Théorie of Lyons. There the whole process and the best
modes of silk manufacture are exhaustively taught. Chemistry and
the arts of colouring silk, with the drawing and designing of patterns,
are included in the lessons. This system of small manufacturers, who
board in their own families the apprentices whom they train to their
trade, was once general throughout France; but within the last fifty
years it has in many districts been superseded by another, known as
the Convent Factory system. It sprang up first among the Jura
Mountains at the small village of Jujurieux. A native of the village, a
poor lad, had worked at Lyons as an apprentice in the establishment
of one of the small master manufacturers so common there. By dint
of industry and intelligence, Jean Bonnet soon became a master
himself, and entering into contracts with important Parisian houses,
in course of time accumulated a large fortune. Returning to his
native place, he found it as he had left it, ugly, decaying, and
wretchedly poor, and resolved to raise it to prosperity. He began by
buying a large piece of ground, on which he built a number of pretty
cottages, a handsome church, and finally a large factory, in which he
resolved to employ only women. He fed, lodged, and clothed the
poor girls whom he received into his employment, paid them small
wages, and taught them the art of silk-weaving along with the
rudiments of education. At the beginning of his enterprise, he had
many difficulties to contend with; his pupils in the first instance often
preferred the rough work of the fields; but he persevered with his
experiment until he had conquered all obstacles, and made Jujurieux
prosperous, and his system a success. The girls, the native material
out of which he formed his workwomen, became, by the aid of a
select body of nuns whom he had enlisted in his service, famous
throughout France for their good conduct and respectability.
The success of this first convent factory led to the establishment of
many others, which with varying fortunes still continue to be worked
very much on the same principle. Not all were so successful as that
of Jujurieux; but many have been so to a great degree, and there
are now three large factories conducted on this principle in the south
of France. Sometimes nuns are employed as teachers, but not
invariably so; in many instances their place is taken by female
superintendents expert at the trade. These women, like the small
master manufacturers, often display the kindliest interest in those
under their charge; and if they see a girl exceptionally clever and
intelligent, will make no inconsiderable personal sacrifices to enable
her to perfect herself in the higher branches of the industry by
becoming a designer of new materials, of patterns, and
combinations of colour, such as are rigidly demanded with every
successive season by the uncompromising tyranny of Fashion.
THE GREAT SHIP-CANAL OF CORINTH.

This work, which, cutting through the Isthmus of Corinth, will be of


sufficient depth and width to allow of the passage of large vessels, is
making rapid progress, employing at present about one thousand
men. The quantity of earth to be excavated will be about twelve
million cubic feet, and of this, about two and a half millions have
already been removed. The depth of the canal is proposed to be
twenty-six feet; and the width at the surface of the water will be
seventy-two feet, except at the entrance, where it will be about
three times that width. The water is already admitted to a distance
of sixteen hundred feet into the land at each end, the depth being
nearly seventeen feet. It is confidently estimated that the canal will
be accomplished in about five years from the present time, judging
by the rate at which it is being carried on. It will be an eminently
useful work when completed, and one calculated to save much
valuable time, by enabling ships to go through the Isthmus, instead
of having to sail round the Morea in order to pass from east to west,
or from west to east—a circumstance that must carry its own
importance in the commercial and maritime world.
‘NONE WILL MISS THEE.’

Few will miss thee, Friend, when thou


For a month in dust hast lain.
Skilful hand, and anxious brow,
Tongue of wisdom, busy brain—
All thou wert shall be forgot,
And thy place shall know thee not.

Shadows from the bending trees


O’er thy lowly head may pass,
Sighs from every wandering breeze
Stir the long, thick, churchyard grass—
Wilt thou heed them? No: thy sleep
Shall be dreamless, calm, and deep.

Some sweet bird may sit and sing


On the marble of thy tomb,
Soon to flit on joyous wing
From that place of death and gloom,
On some bough to warble clear;
But these songs thou shalt not hear.

Some kind voice may sing thy praise,


Passing near thy place of rest,
Fondly talk of ‘other days’—
But no throb within thy breast
Shall respond to words of praise,
Or old thoughts of ‘other days.’

Since so fleeting is thy name,


Talent, beauty, power, and wit,
It were well that without shame
Thou in God’s great book wert writ,
There in golden words to be
Graven for eternity.

Printed and Published by W. & R. Chambers, 47 Paternoster Row,


London, and 339 High Street, Edinburgh.

All Rights Reserved.


*** END OF THE PROJECT GUTENBERG EBOOK CHAMBERS'S
JOURNAL OF POPULAR LITERATURE, SCIENCE, AND ART, FIFTH
SERIES, NO. 140, VOL. III, SEPTEMBER 4, 1886 ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


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

You might also like