100% found this document useful (3 votes)
169 views65 pages

Instant Access to Learning Network Programming with Java 1st Edition Reese Richard M ebook Full Chapters

Learning

Uploaded by

lemetisintiq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
169 views65 pages

Instant Access to Learning Network Programming with Java 1st Edition Reese Richard M ebook Full Chapters

Learning

Uploaded by

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

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

Learning Network Programming with Java 1st Edition


Reese Richard M

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

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


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

Learning Java Functional Programming 1st Edition Reese


Richard M

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

textboxfull.com

Natural Language Processing with Java Community Experience


Distilled 1st Edition Reese Richard M

https://textbookfull.com/product/natural-language-processing-with-
java-community-experience-distilled-1st-edition-reese-richard-m/

textboxfull.com

EJB 3 1 Cookbook 1st Edition M Reese Richard

https://textbookfull.com/product/ejb-3-1-cookbook-1st-edition-m-reese-
richard/

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
Java Network Programming Fourth Edition Harold Elliotte

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

textboxfull.com

Learning Java An Introduction to Real World Programming


with Java Marc Loy

https://textbookfull.com/product/learning-java-an-introduction-to-
real-world-programming-with-java-marc-loy/

textboxfull.com

Learning Java An Introduction to Real World Programming


with Java 5th Edition Marc Loy

https://textbookfull.com/product/learning-java-an-introduction-to-
real-world-programming-with-java-5th-edition-marc-loy/

textboxfull.com

Java for Data Science 1st Edition Reese

https://textbookfull.com/product/java-for-data-science-1st-edition-
reese/

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
© CHB Books
© CHB Books

Learning Network Programming


with Java

Harness the hidden power of Java to build


network-enabled applications with lower network
traffic and faster processes

Richard M Reese

BIRMINGHAM - MUMBAI
© CHB Books
Learning Network Programming with Java

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2015

Production reference: 1141215

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-547-1

www.packtpub.com
© CHB Books

Credits

Author Project Coordinator


Richard M Reese Shipra Chawhan

Reviewer Proofreader
Daniel MÜHLBACHLER Safis Editing

Commissioning Editor Indexer


Veena Pagare Monica Ajmera Mehta

Acquisition Editors Production Coordinator


Vivek Anantharaman Nilesh Mohite
Rahul Nair
Cover Work
Content Development Editor Nilesh Mohite
Arshiya Ayaz Umer

Technical Editor
Humera Shaikh

Copy Editor
Priyanka Ravi
© CHB Books

About the Author

Richard M Reese has worked in both industry and academia. For 17 years, he
worked in the telephone and aerospace industries, serving in several capacities,
including research and development, software development, supervision, and
training. He currently teaches at Tarleton State University, where he has the
opportunity to apply his years of industry experience to enhance his teaching.

Richard has written several Java books and a C Pointer book. He uses a concise and
easy-to-follow approach to topics at hand. His Java books have addressed EJB 3.1,
updates to Java 7 and 8, certification, functional programming, jMonkeyEngine, and
natural language processing.

I would like to thank my daughter, Jennifer, for her numerous


reviews and contributions; my wife, Karla, for her continued support;
and to the staff of Packt for their work in making this a better book.
© CHB Books

About the Reviewer

Daniel MÜHLBACHLER got interested in computer science shortly after


entering high school, where he later developed web applications as part of a
scholarship system for outstanding pupils.

He has a profound knowledge of web development (PHP, HTML, CSS/LESS, and


AngularJS), and has worked with a variety of other programming languages and
systems, such as Java/Groovy, Grails, Objective-C and Swift, Matlab, C (with Cilk),
Node.js, and Linux servers.

Furthermore, he works with some database management systems based on SQL, and
also some NoSQL systems, such as MongoDB, and SOLR. This is also reflected in
several projects that he is currently involved in at Catalysts GmbH.

After studying abroad as an exchange student in the United Kingdom, he completed


his bachelor's degree at Johannes Kepler University in Linz, Austria, with a thesis
on aerosol satellite data processing for mobile visualization. This is where he also
became familiar with processing large amounts of data.

Daniel enjoys solving challenging problems and is always keen on working with new
technologies, especially related to the fields of big data, functional programming,
optimization, and NoSQL databases.

More detailed information about his experience, as well as his contact details, can be
found at www.muehlbachler.org and www.linkedin.com/in/danielmuehlbachler.
© CHB Books

www.PacktPub.com

Support files, eBooks, discount offers, and more


For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.
TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.
© CHB Books

Table of Contents
Preface vii
Chapter 1: Getting Started with Network Programming 1
Network addressing using the InetAddress class 3
NIO support 5
Using the URLConnection class 5
Using the URLConnection class with buffers and channels 6
The client/server architecture 7
Creating a simple echo server 8
Creating a simple echo client 10
Using Java 8 to support the echo server and client 12
UDP and multicasting 14
Creating a multicast server 14
Creating the multicast client 15
Scalability 17
Creating a threaded server 17
Using the threaded server 19
Security 21
Creating a SSL server 21
Creating an SSL client 22
Generating secure keys 23
Summary 25
Chapter 2: Network Addressing 27
Networking basics 27
Understanding network basics 29
Network architectures and protocols 30
Using the NetworkInterface class 32
Getting a MAC address 35
Getting a specific MAC address 35

[i]
© CHB Books
Table of Contents

Getting multiple MAC addresses 36


Network addressing concepts 37
URL/URI/URN 37
Using the URI class 39
Creating URI instances 39
Splitting apart a URI 40
Using the URL class 41
Creating URL instances 42
Splitting apart a URL 42
IP addresses and the InetAddress class 45
Obtaining information about an address 45
Address scoping issues 47
Testing reachability 48
Introducing the Inet4Address 49
Private addresses in IPv4 50
IPv4 address types 50
The Inet4Address class 51
Special IPv4 addresses 51
Introducing the Inet6Address class 52
Private addresses in IPv6 52
The Inet6Address class 53
Special IPv6 addresses 53
Testing for the IP address type 53
Using IPv4-compatible IPv6 addresses 54
Controlling network properties 56
Summary 56
Chapter 3: NIO Support for Networking 57
Java NIO 57
Introduction to buffers 59
Using channels with a time server 60
Creating a time server 61
Creating a time client 62
The chat server/client applications 63
The chat server 64
The chat client 66
Server/client interaction 67
The HelperMethods class 68
Handling variable length messages 69
Running the chat server/client application 71
Handling multiple clients 72
The parts server 72
The parts client handler 74
The parts client 75

[ ii ]
© CHB Books
Running the parts client/server
Table of Contents

76
Asynchronous socket channels 78
Creating the asynchronous server socket channel server 79
Creating the asynchronous socket channel client 81
Other buffer operations 83
Bulk data transfer 83
Using a view 85
Using read-only buffers 86
Controlling socket options 86
Summary 87
Chapter 4: Client/Server Development 89
The HTTP protocol structure 89
The nature of HTTP messages 91
Initial request line format 92
Header lines 94
Message body 94
Client/Server interaction example 95
Java socket support for HTTP client/server applications 95
Building a simple HTTP server 96
Building a simple HTTP client 100
Client/server development using standard Java classes 102
Using the HttpURLConnection class 102
URL encoding 105
Using the HTTPServer class 106
Implementing a simple HTTPServer class 108
Managing response headers 112
Open source Java HTTP servers 113
Server configuration 115
Handling cookies 116
Summary 117
Chapter 5: Peer-to-Peer Networks 119
P2P functions/characteristics 120
Applications-based P2P networks 122
Java support for P2P applications 123
Distributed hash tables 123
DHT components 124
DHT implementations 126
Using JDHT 126
Using FreePastry 128
The FreePastry demonstration 129
Understanding the FreePastryExample class 129

[ iii ]
© CHB Books
Table of Contents

Understanding the FreePastryApplication class 131


Sending a message to a specific node 135
Summary 137
Chapter 6: UDP and Multicasting 139
Java support for UDP 140
TCP versus UDP 142
UDP client/server 142
The UDP server application 143
The UDP client application 145
The UDP client/server in action 146
Channel support for UDP 148
The UDP echo server application 148
The UDP echo client application 150
The UDP echo client/server in action 152
UDP multicasting 153
The UDP multicast server 153
The UDP multicast client 154
The UDP multicast client/server in action 156
UDP multicasting with channels 156
The UDP channel multicast server 159
The UDP channel multicast client 160
The UDP channel multicast client/server in action 162
UDP streaming 162
The UDP audio server implementation 163
The UDP audio client implementation 165
Summary 168
Chapter 7: Network Scalability 169
Multithreaded server overview 170
The thread-per-request approach 172
The thread-per-request server 173
The thread-per-request client 175
The thread-per-request applications in action 175
Thread-per-connection approach 178
The thread-per-connection server 178
The thread-per-connection client 179
The thread-per-connection applications in action 179
Thread pools 180
The ThreadPoolExecutor class characteristics 181
Simple thread pool server 182
Simple thread pool client 184

[ iv ]
© CHB Books
The thread pool client/server in action
Table of Contents

185
Thread pool with Callable 186
Using a Callable 186
Using a Future 188
Using the HttpServer executor 189
Using a selector 190
Creating the selector 191
Registering a channel 191
Using the selector to support a time client/server 193
The channel time server 193
The date and time client application 197
The date and time server/client in action 197
Handling network timeouts 199
Summary 199
Chapter 8: Network Security 201
Security 201
Secure communication terminology 202
Encryption basics 203
Symmetric encryption techniques 204
Generating a key 204
Encrypting text using a symmetric key 205
Decrypting text 206
Asymmetric encryption techniques 206
Generating and saving asymmetric keys 208
Encrypting/decrypting text using an asymmetric key 209
Saving asymmetric keys to a file 210
Creating a keystore 213
Creating and maintaining a keystore with keytool 213
Keytool command-line arguments 216
Creating and maintaining a keystore with Java 219
Symmetric encryption client/server 221
Symmetric server application 222
Symmetric client application 224
Symmetric client/server in action 226
Asymmetric encryption client/server 227
Asymmetric server application 227
Asymmetric client application 228
Asymmetric client/server in action 230
TLS/SSL 230
SSL server 231
SSL client 233
SSL client/server in action 234

[v]
© CHB Books
Table of Contents

Secure hash functions 235


Summary 237
Chapter 9: Network Interoperability 239
Byte order in Java 240
Interfacing with other languages 242
Interfacing with JVM based languages 242
Interfacing with non-JVM languages 243
Communication through simple sockets 244
The Java server 244
The C# client 245
The client/server in action 247
Interoperability through middleware 248
Creating a RESTful service 249
Testing the RESTful service 253
Creating a RESTful client 256
Summary 260
Index 261

[ vi ]
© CHB Books

Preface
The world is becoming interconnected on an unprecedented scale with more services
being provided on the Internet. Applications ranging from business transactions
to embedded applications, such as those found in refrigerators, are connecting to
the Internet. With isolated applications no longer being the norm, it is becoming
increasingly important for applications to be network enabled.

The goal of this book is to provide the reader with the necessary skills to develop
Java applications that connect and work with other applications and services across
a network. You will be introduced to a wide range of networking options that
are available using Java, which will enable you to develop applications using the
appropriate technology for the task at hand.

What this book covers


Chapter 1, Getting Started with Network Programming, introduces the essential network
terminology and concepts. The networking support that Java provides is illustrated
with brief examples. A simple client/server application is presented along with a
threaded version of the server.

Chapter 2, Network Addressing, explains how nodes on a network use addresses. How
Java represents these addresses is introduced along with support for IPv4 and IPv6.
This chapter also covers how Java can configure various network properties.

Chapter 3, NIO Support for Networking, explains how the NIO package provides
support for communication using buffers and channels. These techniques are
illustrated with a client/server application. The support that NIO provides for
asynchronous communication is also demonstrated.

[ vii ]
© CHB Books
Preface

Chapter 4, Client/Server Development, covers how HTTP is an important and


widely-used protocol. Java provides support for this protocol in a variety of ways.
These techniques are illustrated along with a demonstration of how cookies are
handled in Java.

Chapter 5, Peer-to-Peer Networks, discusses how peer-to-peer networks provide a flexible


alternative to the traditional client/server architecture. The basic peer-to-peer concepts
are introduced along with demonstrations of how Java supports this architecture.
FreePastry is used to illustrate one open source peer-to-peer solution framework.

Chapter 6, UDP and Multicasting, explains how UDP is an alternative to TCP. It


provides a less reliable but more efficient way for applications to communicate
across the Internet. Java's extensive support for this protocol is demonstrated,
including NIO support, and how UDP can support streaming media.

Chapter 7, Network Scalability, explains how, as more demands are placed on a server,
systems need to scale to address these demands. Several threading techniques
supporting this need are demonstrated, including thread pools, futures, and the
NIO's selector.

Chapter 8, Network Security, discusses how applications need to protect against a


variety of threats. This is supported in Java using encryption and secure hashing
techniques. Symmetric and asymmetric encryption techniques are illustrated. In
addition, the use of TLS/SSL is demonstrated.

Chapter 9, Network Interoperability, covers how Java applications may need to


exchange information with other applications that are written in different languages.
The issues that impact an application's interoperability are examined, including byte
order. Communication between different implementations is demonstrated using
sockets and middleware.

What you need for this book


Java SDK 1.8 is needed for the network programming examples that are encountered
in the book. An IDE, such as NetBeans or Eclipse, is recommended. NetBeans IDE
8.0.2 EE edition is used to illustrate the development of a web service.

[ viii ]
© CHB Books Preface

Who this book is for


This book is for developers who are already proficient in Java and want to learn
how to develop network-enabled Java applications. Familiarity with basic Java and
object-oriented programming concepts is all that is needed. You will learn the basics
of network programming and how to use a multitude of different sockets to create
secure and scalable applications.

Conventions
In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of
their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"The SSLSocketFactory class' getDefault returns an SSLSocketFactory instance
whose createSocket creates a socket that is connected to the secure echo server."

A block of code is set as follows:


public class ThreadedEchoServer implements Runnable {
private static Socket clientSocket;

public ThreadedEchoServer(Socket clientSocket) {


this.clientSocket = clientSocket;
}
...
}

Any command-line input or output is written as follows:


Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: First Last
What is the name of your organizational unit?
[Unknown]: packt
What is the name of your organization?
[Unknown]: publishing
What is the name of your City or Locality?
[Unknown]: home

[ ix ]
© CHB Books
Preface

What is the name of your State or Province?


[Unknown]: calm
What is the two-letter country code for this unit?
[Unknown]: me
Is CN=First Last, OU=packt, O=publishing, L=home, ST=calm, C=me correct?
[no]: y

Enter key password for <mykey>


(RETURN if same as keystore password):

New terms and important words are shown in bold. Words that you see on the
screen, for example, in menus or dialog boxes, appear in the text like this: "Once
NetBeans has been installed, start it and then create a new project from the File |
New Project… menu item."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it helps
us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention


the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.

[x]
© CHB Books Preface

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


You can download the example code files from your account at http://www.
packtpub.com for all the Packt Publishing books you have purchased. If you
purchased this book elsewhere, you can visit http://www.packtpub.com/support
and register to have the files e-mailed directly to you.

Downloading the color images of this book


We also provide you with a PDF file that has color images of the screenshots/
diagrams used in this book. The color images will help you better understand the
changes in the output. You can download this file from: https://www.packtpub.
com/sites/default/files/downloads/LearningNetworkProgrammingwithJava_
Graphics.pdf.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or added
to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/


content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

[ xi ]
© CHB Books
Preface

Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at [email protected] with a link to the suspected


pirated material.

We appreciate your help in protecting our authors and our ability to bring
you valuable content.

Questions
If you have a problem with any aspect of this book, you can contact us at
[email protected], and we will do our best to address the problem.

[ xii ]
© CHB Books

Getting Started with


Network Programming
Access to networks (the Internet in particular) is becoming an important and often
necessary feature of applications. Applications frequently need to access and
provide services. As the Internet of Things (IoT) connects more and more devices,
understanding how to access networks becomes crucial.

The important factors that have been the driving forces for more network
applications include the availability of faster networks with greater bandwidth.
This has made it possible to transmit wider ranges of data, such as video streams.
In recent years, we have seen an increase in connectivity, whether it has been for
new services, more extensive social interactions, or games. Knowing how to develop
network applications is an important development skill.

In this chapter, we will cover the basics of Network programming:

• Why networking is important


• The support that Java provides
• Simple programs to address basic network operations
• Basic networking terminology
• A simple server/client application
• Using a thread to support a server

Throughout this book, you will be exposed to many network concepts, ideas, patterns,
and implementation strategies using both older and newer Java technologies.
Network connections occur at a low level using sockets, and at a much higher level
using a multitude of protocols. Communications can be synchronous requiring
careful coordination of requests and responses, or they can be asynchronous where
other activities are performed until the response has been submitted.

[1]
© CHB Books
Getting Started with Network Programming

These and other concepts are addressed through a series of chapters, each focusing
on a specific topic. The chapters complement each other by elaborating on concepts
that were previously introduced, whenever possible. Numerous code examples are
used whenever possible to further your understanding of the topic.

Central to accessing a service is knowing or discovering its address. This address


may be human readable, such as www.packtpub.com, or in the form of an IP address
such as 83.166.169.231. Internet Protocol (IP) is a low-level addressing scheme
that is used to access information on the Internet. Addressing has long used IPv4
to access resources. However, these addresses are all but gone. The newer IPv6 is
available to provide a larger range of addresses. The basics of network addressing
and how they can be managed in Java is the focus of Chapter 2, Network Addressing.

The intent of network communication is to transfer information to and from other


applications. This is facilitated using buffers and channels. Buffers hold information
temporarily until it can be processed by an application. Channels are an abstraction
that simplifies communications between applications. The NIO and NIO.2 packages
provide much of the support for buffers and channels. We will explore these
techniques along with other techniques, such as blocking and non-blocking IO, in
Chapter 3, NIO Support for Networking.

Services are provided by servers. An example of this is the simple echo server, which
retransmits what it was sent. More sophisticated servers, such as HTTP servers, can
support extensive services to meet a wide range of needs. The client/server model
and its Java support are covered in Chapter 3, NIO Support for Networking.

Another service model is the peer-to-peer (P2P) model. In this architecture, there is
no central server, but rather a network of applications that communicate to provide
a service. This model is represented by applications, such as BitTorrent, Skype, and
BBC's iPlayer. While much of the support that is required for the development of
these types of applications is beyond the scope of this book, Chapter 4, Client/Server
Development, explores P2P issues and the support provided by Java and JXTA.

IP is used at a low level to send and receive packets of information across a


network. We will also demonstrate the use of User Datagram Protocol (UDP) and
Transmission Control Protocol (TCP) communication protocols. These protocols
are layered on top of IP. UDP is used to broadcast short packets or messages with no
guarantee of reliable delivery. TCP is used more commonly and provides a higher
level of service than that of UDP. We will cover the use of these related technologies
in Chapter 5, Peer-to-Peer Networks.

[2]
© CHB Books
A service will often be faced with varying levels of demand placed on it due to a
Chapter 1

number of factors. Its load may vary by the time of the day. As it becomes more
popular, its overall demand will also increase. The server will need to scale to meet
increases and decreases in its load. Threads and thread pools have been used to support
this effort. These and other technologies are the focus of Chapter 6, UDP and Multicasting.

Increasingly, applications need to be secure against attacks by hackers. When it is


connected to a network, this threat increases. In Chapter 7, Network Scalability, we will
explore many of the techniques available to support secure Java applications. Among
these is the Secure Socket Level (SSL), and how Java supports it.

Applications rarely work in isolation. Hence, they need to use networks to access
other applications. However, not all applications are written in Java. Networking
with these applications can pose special problems ranging from how the bytes of a
data type are organized to the interface supported by the application. It is common
to work with specialized protocols, such as HTTP, and WSDL. The last chapter of
this book examines these issues from a Java perspective.

We will demonstrate both older and newer Java technologies. Understanding the
older technologies may be necessary in order to maintain older code, and it can
provide insight into why the newer technologies were developed. We will also
complement our examples using many of the Java 8 functional programming
techniques. Using Java 8 examples along with pre-Java 8 implementations, we can
learn how to use Java 8 and be better informed as to when it can and should be used.

It is not the intent to fully explain the newer Java 8 technologies, such as lambda
expressions, and streams. However, the use of Java 8 examples will provide an
insight into how they can be used to support networked applications.

The remainder of this chapter touches on many of the network technologies that are
explored in this book. You will be introduced to the basics of these techniques, and you
should find them easy to understand. However, there are a few places where time does
not permit us to fully explore and explain these concepts. These issues will be addressed
in subsequent chapters. So, let's begin our exploration with network addressing.

Network addressing using the


InetAddress class
An IP address is represented by the InetAddress class. Addresses can be either
unicast where it identifies a specific address, or it can be multicast, where a message
is sent to more than one address.

[3]
© CHB Books
Getting Started with Network Programming

The InetAddress class has no public constructors. To get an instance, use one of
the several static get type methods. For example, the getByName method takes a
string representing the address as shown next. The string in this case is a Uniform
Resource Locator (URL):
InetAddress address =
InetAddress.getByName("www.packtpub.com");
System.out.println(address);

Downloading the example code


You can download the example code files for all
Packt books you have purchased from your account
at http://www.packtpub.com. If you purchased
this book elsewhere, you can visit http://www.
packtpub.com/support and register to have the
files e-mailed directly to you.

This will display the following results:

www.packtpub.com/83.166.169.231

The number attached to the end of the name is the IP address. This address uniquely
identifies an entity on the Internet.

If we need other information about the address, we can use one of several methods,
as illustrated here:
System.out.println("CanonicalHostName: "
+ address.getCanonicalHostName());
System.out.println("HostAddress: " +
address.getHostAddress());
System.out.println("HostName: " + address.getHostName());

This produces the following output when executed:

CanonicalHostName: 83.166.169.231

HostAddress: 83.166.169.231

HostName: www.packtpub.com

To test to see whether this address is reachable, use the isReachable method as
shown next. Its argument specifies how long to wait before deciding that the address
cannot be reached. The argument is the number of milliseconds to wait:
address.isReachable(10000);

[4]
© CHB Books
There are also the Inet4Address and Inet6Address classes that support
Chapter 1

IPv4 and IPv6 addresses, respectively. We will explain their use in Chapter 2,
Network Addressing.

Once we have obtained an address, we can use it to support network access, such as
with servers. Before we demonstrate its use in this context, let's examine how we can
obtain and process data from a connection.

NIO support
The java.io, java.nio, and java.nio subpackages provide most of the Java
support for IO processing. We will examine the support that these packages provide
for network access in Chapter 3, NIO Support for Networking. Here, we will focus on
the basic aspects of the java.nio package.

There are three key concepts used in the NIO package:

• Channel: This represents a stream of data between applications


• Buffer: This works with a channel to process data
• Selector: This is a technology that allows a single thread to handle multiple
channels

A channel and a buffer are typically associated with each other. Data may be transferred
from a channel to a buffer or from a buffer to a channel. The buffer, as its name
implies, is a temporary repository for information. The selector is useful in supporting
application scalability, and this will be discussed in Chapter 7, Network Scalability.

There are four primary channels:

• FileChannel: This works with a file


• DatagramChannel: This supports UDP communications
• SocketChannel: This is used with a TCP client
• ServerSocketChannel: This is used with a TCP server

There are several buffer classes that support primitive data types, such as character,
integer, and float.

Using the URLConnection class


A simple way of accessing a server is to use the URLConnection class. This class
represents a connection between an application and a URL instance. A URL instance
represents a resource on the Internet.

[5]
© CHB Books
Getting Started with Network Programming

In the next example, a URL instance is created for the Google website. Using
the URL class' openConnection method, a URLConnection instance is created.
A BufferedReader instance is used to read lines from the connection that is
then displayed:
try {
URL url = new URL("http://www.google.com");
URLConnection urlConnection = url.openConnection();
BufferedReader br = new BufferedReader(
new InputStreamReader(
urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException ex) {
// Handle exceptions
}

The output is rather lengthy, so only part of the first line is shown here:

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" ...

The URLConnection class hides some of the complexity of accessing HTTP servers.

Using the URLConnection class with buffers


and channels
We can rework the previous example to illustrate the use of channels and buffers. The
URLConnection instance is created as before. We will create a ReadableByteChannel
instance and then a ByteBuffer instance, as illustrated in the next example. The
ReadableByteChannel instance allows us to read from the site using its read method.
A ByteBuffer instance receives data from the channel and is used as the argument of
the read method. The buffer created holds 64 bytes at a time.

The read method returns the number of bytes read. The ByteBuffer class' array
method returns an array of bytes, which is used as the argument of the String class'
constructor. This is used to display the data read. The clear method is used to reset
the buffer so that it can be used again:
try {
URL url = new URL("http://www.google.com");
URLConnection urlConnection = url.openConnection();

[6]
© CHB Books InputStream inputStream = urlConnection.getInputStream();
Chapter 1

ReadableByteChannel channel =
Channels.newChannel(inputStream);
ByteBuffer buffer = ByteBuffer.allocate(64);
String line = null;
while (channel.read(buffer) > 0) {
System.out.println(new String(buffer.array()));
buffer.clear();
}
channel.close();
} catch (IOException ex) {
// Handle exceptions
}

The first line of output is shown next. This produces the same output as before, but it
is restricted to displaying 64 bytes at a time:

<!doctype html><html itemscope="" itemtype="http://schema.org/We

The Channel class and its derived classes provide an improved technique to access
data found on a network than data provided by older technologies. We will be seeing
more of this class.

The client/server architecture


There are several ways of creating servers using Java. We will illustrate a couple
of simple approaches and postpone a detailed discussion of these techniques until
Chapter 4, Client/Server Development. Both a client and a server will be created.

A server is installed on a machine with an IP address. It is possible for more than


one server to be running on a machine at any given time. When the operating system
receives a request for a service on a machine, it will also receive a port number. The
port number will identify the server to where the request should be forwarded.
A server is, thus, identified by its combination of IP address and port number.

Typically, a client will issue a request to a server. The server will receive the request
and send back a response. The nature of the request/response and the protocol used
for communication is dependent on the client/server. Sometimes a well-documented
protocol, such as the Hypertext Transfer Protocol (HTTP), is used. For simpler
architectures, a series of text messages are sent back and forth.

[7]
© CHB Books
Getting Started with Network Programming

For the server to communicate with an application making a request, specialized


software is used to send and receive messages. This software is called a socket. One
socket is found on the client side, and the other socket is located on the server side.
When they connect, communication is possible. There are several different types of
sockets. These include datagram sockets; stream sockets, which frequently use TCP;
and raw sockets, which normally work at the IP level. We will focus on TCP sockets
for our client/server application.

Specifically, we will create a simple echo server. This server will receive a text
message from a client and will immediately send it back to that client. The simplicity
of this server allows us to focus on the client-server basics.

Creating a simple echo server


We will start with the definition of the SimpleEchoServer class as shown next. In
the main method, an initial server message will be displayed:
public class SimpleEchoServer {
public static void main(String[] args) {
System.out.println("Simple Echo Server");
...
}
}

The remainder of the method's body consists of a series of try blocks to handle
exceptions. In the first try block, a ServerSocket instance is created using 6000 as
its parameter. The ServerSocket class is a specialized socket that is used by a server
to listen for client requests. Its argument is its port number. The IP of the machine on
which the server is located is not necessarily of interest to the server, but the client
will ultimately need to know this IP address.

In the next code sequence, an instance of the ServerSocket class is created and
its accept method is called. The ServerSocket will block this call until it receives
a request from a client. Blocking means that the program is suspended until the
method returns. When a request is received, the accept method will return a Socket
class instance, which represents the connection between that client and the server.
They can now send and receive messages:
try (ServerSocket serverSocket = new ServerSocket(6000)){
System.out.println("Waiting for connection.....");
Socket clientSocket = serverSocket.accept();
System.out.println("Connected to client");
...

[8]
© CHB Books} catch (IOException ex) {
Chapter 1

// Handle exceptions
}

After this client socket has been created, we can process the message sent to the
server. As we are dealing with text, we will use a BufferedReader instance to read
the message from the client. This is created using the client socket's getInputStream
method. We will use a PrintWriter instance to reply to the client. This is created
using the client socket's getOutputStream method, shown as follows:
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true)) {
...
}
}

The second argument to the PrintWriter constructor is set to true. This means that
text sent using the out object will automatically be flushed after each use.

When text is written to a socket, it will sit in a buffer until either the buffer is full
or a flush method is called. Performing automatic flushing saves us from having to
remember to flush the buffer, but it can result in excessive flushing, whereas a single
flush issued after the last write is performed, will also do.

The next code segment completes the server. The readLine method reads a line at a
time from the client. This text is displayed and then sent back to the client using the
out object:

String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println("Server: " + inputLine);
out.println(inputLine);
}

Before we demonstrate the server in action, we need to create a client application to


use with it.

[9]
© CHB Books
Getting Started with Network Programming

Creating a simple echo client


We start with the declaration of a SimpleEchoClient class where in the main method,
a message is displayed indicating the application's start that is shown as follows:
public class SimpleEchoClient {
public static void main(String args[]) {
System.out.println("Simple Echo Client");
...
}
}

A Socket instance needs to be created to connect to the server. In the following


example, it is assumed that the server and the client are running on the same
machine. The InetAddress class' static getLocalHost method returns this address,
which is then used in the Socket class's constructor along with port 6000. If they are
located on different machines, then the server's address needs to be used instead.
As with the server, an instance of the PrintWriter and BufferedReader classes are
created to allow text to be sent to and from the server:
try {
System.out.println("Waiting for connection.....");
InetAddress localAddress = InetAddress.getLocalHost();

try (Socket clientSocket = new Socket(localAddress, 6000);


PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()))) {
...
}
} catch (IOException ex) {
// Handle exceptions
}

Localhost refers to the current machine. This has a specific


IP address: 127.0.0.1. While a machine may be associated
with an additional IP address, every machine can reach itself
using this localhost address.

[ 10 ]
Other documents randomly have
different content
the first time, Emmie saw her opportunity. She know that
the sleep might probably last some time; so she coaxed her
mother into a comfortable chair by the drawing-room fire,
ordered up the tea-tray earlier than usual, and waited on
her assiduously, unaware how closely she was herself
watched, for she hardly dared to lift her dropped eyelids.

There came presently a soft, "My poor little Emmie!"

"O mother!"

Emmie knelt down on the rug with an arm round Mrs.


Lucas.

"I have always feared it might happen again, some day . . .


It is so like a disease. One can hardly expect no recurrence
. . . Yet some would tell me that is a want of trust. And I
know he can be kept from it! . . . Still—time after time—this
has come."

"Mr. Trevelyan was so nice, wasn't he?"

"I think he will be an immense help. He promises me to well


look after your father. He is just the man for it—kind and
thoughtful, and a thorough gentleman. And so very good."

"Mother—"

Something in the voice made Mrs. Lucas look into her


daughter's face.

"Mother—Sir Cyril came yesterday—when you were busy,


you know. And—"

"He did not see your father?"


"No. I knew you were both in the morning-room. I did offer
to call you, but he said there was no need. And I knew you
could not well come. But, mother—he—"

The crimsoning face drooped, and Mrs. Lucas' heart beat


fast. She drew Emmie closer.

"Yes. He—?"

"He said—something. Something that I must tell you . . . I


always tell you everything . . . He asked—He wants me—to
be his wife."

Mrs. Lucas could hardly control her thrill of astonishment.


She had feared some trembling avowal of Emmie's feelings
towards Sir Cyril; but she had not looked for this. It had
been a settled matter in her imagination that Sir Cyril was
in love with Jean Trevelyan.

"Tell me all, darling."

"I didn't know it was coming—of course. I couldn't think


what he meant at first—and I was so full of—that, you know
—but I found he was really in earnest. He says—says—he
loves me!"—in a whisper. "And he wants me to marry him."

"And you said—?"

"I couldn't answer him at once. How could I—before I had


spoken to you? I didn't know what to say; and it seemed so
funny. Why, I'm only a child. I asked him to let me have till
to-morrow; and he said he supposed I wanted to get used
to the idea. And he told me to pity his suspense. But it does
seem odd that he should care for me—for little Emmie
Lucas! He is so clever and handsome, and everybody likes
him."
"Including Emmie?"

"Yes. O yes—I like him." Emmie looked frankly up. "He is so


nice and kind to poor father. I don't see how I could help
liking him. I like him very much indeed. I should hate to do
anything to give him pain."

"Sometimes to give a passing pain is the truest kindness.


Emmie, the question really is not whether you like Sir Cyril,
but whether you love him."

Emmie's face flushed all over again.

"But—"

"But what?"

"People don't always begin with that, do they? I mean—


doesn't it come after they are married, sometimes?"

"Sometimes; but the risk is serious."

Emmie sighed.

"He is so nice," she said, "so very very nice and pleasant.
And I do look up to him really, because he is so clever. I like
him—oh, ever so much. It's almost a little like loving. Not
like the sort of love I have for you, of course; because I
don't think anything ever could be the same as that—but
still—I do like to see him come in, and it would be very dull
if he never came. Don't you think it would?"

"The question is not what I think, my dear."

"Well—I think it would—really. Do you know, mother, he


didn't seem afraid about my answer!"

"No? He did not seem very eager or anxious, you mean?"


"No—not exactly—only so kind and pleasant. He saw I was
in trouble, mother. And I do think it grieved him. And if he
cares so much for me—And if I like him so much—"

"No true man could be satisfied with no more."

"Couldn't he?" with a look of childish sweetness. "But—"


tears filling her eyes—"I'm afraid it does look rather
tempting. Everything would be so different. Different for
you and father. You would have plenty of friends."

"No, my darling; don't deceive yourself. Lady Lucas might


give up Sir Cyril for marrying you. She would not accept us
because you married Sir Cyril."

"Wouldn't she? I thought—perhaps—"

"Don't think of us at all. Or, if you do, think what it would be


to us to lose our one sunbeam. That should not stand in
your way, if it were a question of your real happiness. But
—"

"Oh!" in a startled tone. "You could not get on without me,


of course. I never thought of that. There would be nobody
to walk with my father. You can't go any distance—and
fancy him wandering about alone . . . But then I should be
so near! I could run in every day, and look after him almost
the same as now."

"If you were Sir Cyril's wife, your duty would be to him, not
to us. He is a man of leisure, and his wife will have her time
well filled. Dear Emmie, you must put the thought of us
quite aside, and think only of yourself and him. Only you
and him! Could you promise to love him all your life—first
and best? To love him?"
"Not so much as I love you, of course, mother! How could I
possibly?"—with a look of infantine sweetness. "And I
should be miserable if I couldn't see you every day, and tell
you every single thing as I do now. But I don't like to make
him unhappy."

"You must do what is right, and leave his unhappiness to


take care of itself. I am not sure that it will be very deep.
There may be a touch of self-deception in this sudden fancy
. . . Did it never occur to you that he thinks a great deal of
Jean Trevelyan?"

Emmie laughed. "Yes, indeed he does. He is always talking


of her. It is the funniest thing—but whatever we happen to
be speaking about, he always twists the subject round, so
as to bring in her name. I really do think it is that, that has
kept me from seeing how much he cared for me . . . It's
funny, mother . . . And, of course, a man can't care for two
girls at once—in that way, I mean . . . And, of course, if he
did care for her, he wouldn't ask me to marry him."

"If he knew that he cared for her most. People do not


always fully know their own minds. It has been a life-long
affection, and perhaps he does not measure the strength of
it. His perpetual reference to her ideas and opinions has a
suspicious look. No doubt he has been captivated for the
moment by this dear little face—" kissing it. "But suppose
there were a mistake—and suppose he found out by-and-by
—"

"Yes: I see! And you think I had better say 'No' at once?"

"I think you must decide for yourself; but I am very much
afraid of a hasty 'Yes,'—for your sake, and for his. I am
afraid you might both regret it."
"Yes; I understand. O no; it wouldn't do! Mother, I really am
glad. Perhaps I'm a little sorry too, because the Brow and
everything would be so nice—except Miss Devereux and
Lady Lucas! I should like it so much for you and my father .
. . But, of course, that isn't enough. I mean it wouldn't be
right to marry him for the sake of anybody else! . . . And
somehow, I can't think of Sir Cyril as—as—a husband!"—
blushing furiously. "I like him very much indeed, just
coming in and out. But I almost think—I'm afraid I should
get just a little tired of him, if it were always and always
going on."

"And suppose poor Sir Cyril—after losing friends and


offending relatives by marrying—suppose he should find the
wife, for whom he had given up so much, getting only a
little tired of him? Only a little bored with his talk—and
impatient of his companionship—and careless about
pleasing him—perhaps even pettish and fractious, in return
for—?"

"Mother, you needn't go on! I see now quite quite plainly! I


didn't understand before. It would be horrid and cruel of me
to marry him, feeling as I do. O no—because I don't really
love him, and I don't believe I ever could! I'll write a note
this minute; and don't you think we might send it—not keep
him another whole night in suspense? I suppose he is in a
little suspense just now, you know—though I dare say he
will get over it soon."

It had indeed been a day of suspense for Cyril, though not


precisely that fashion of suspense which Emmeline
innocently pictured to herself. How to live through the
dragging hours was a problem not easily solved. Most
young men in his condition would at least have had the help
of enforced occupation, but Cyril had abundant leisure to
suffer his worst.

Sybella's was not a soothing companionship. She fretted


him with questions and surmises, was annoyed when he
told her nothing, and defended herself with her usual
verbosity from charges which nobody had made, turning
everything into an argument.

To escape from home-friction, Cyril walked from breakfast


until lunch, after which he vanished into his smoking-den
for an hour, and then went off for a four hours' ride, barely
returning in time for dinner, which indeed had to wait ten
minutes while he dressed.

"You never used to be unpunctual, Cyril!"

"I dare say not," Cyril answered.

"It is a very bad habit. It grows upon people."

"It will grow upon me, of course."

"My dear aunt always trained me to be scrupulously


punctual. She never allowed slipshod ways. But your dear
father was different. He never could be in time for things. I
hope you do not mean to take after him."

"Might do worse!" muttered the chafed Cyril. He had tender


recollections of his father, and could ill endure to hear him
discussed by Sybella.

"What do you say? I really cannot hear when you mumble


so, Cyril . . . Is there anything wrong with the soup? You
are not taking any . . . Lady Lucas has been here to-day,
calling. And she told me a most dreadful thing. About that
miserable nephew of hers—"

"Lady Lucas is an awful old gossip."

"Really, Cyril—"

"There's no need, at all events, to retail her scandal in


public."

Something in the suppressed voice warned even Sybella to


desist for a while.

When dessert was on the table, and the man had vanished,
she began anew—

"I must tell you now! It is not a matter of choice, but of


duty—a positive necessity, for your own sake. As for Pearce
hearing—everybody will know, so I do not see that it makes
much difference. That wretched man, Captain Lucas—No, I
cannot be interrupted, Cyril! I really must for once speak
out! That wretched man, Captain Lucas, was actually—
absolutely—carried home yesterday evening by two
policemen—dead drunk! Yes, it is a fact! There can be no
possible mistake. It is a most fearful disgrace. Everybody is
talking about it, and pitying Lady Lucas. He was seen
reeling about in the streets, like any common creature out
of a public-house."

"I don't see how he could manage to reel about, if he were


dead drunk!"

"Really, Cyril! To take it in such a way! To make a joke of it,


almost! And such a dreadful thing! . . . And you can actually
stoop to call that man your friend! Captain Lucas—a
drunkard—the friend of Sir Cyril Devereux!" Sybella spoke
with more force of expression than she usually had at
command.

The arrow went home: only Cyril's brain substituted the


word "father-in-law" for "friend." He had grown white, and
his brows were drawn sternly together. He cracked half-a-
dozen nuts in quick succession, tossing each aside, and
asked only—

"Have you done?"

"I suppose you don't believe me, but it is true. Perfectly


true. As you will find to your cost. Some day," asserted
Sybella, with agitated breaks.

"The main fact is true. Lady Lucas has only improved upon
it a little—not more than one might reasonably expect! He
was not 'dead drunk,' and he did not require to be carried, I
believe—but unhappily, he did take too much."

"As he does constantly—every other day."

"You are misinformed. He has not failed once in the last


year and more—till now."

"My dear Cyril! If I did not know it on the best authority—"

Cyril's mutter was unintelligible.

"I assure you, I know it for a fact. He is constantly in that


state. Of course, nobody sees him so, because his wife
generally contrives to hush it up, and not to let him go out.
I suppose, he escaped for once from her control . . . If you
were only not so easily imposed upon, my dear Cyril! . . .
Lady Lucas tells me his wife is a most designing person.
She says there can be no doubt whatever that they are
hoping to make a catch of you! That the young lady is
deliberately setting her cap—to use an expression which—"

Cyril could endure no more. He was in a sick tumult of


wrath and wretchedness—of wrath with himself, and of
wretchedness about his own action, far more than with or
about Sybella. She was only the gadfly, adding to his
misery; but when one is already strung to intense
endurance, a gadfly in addition becomes unbearable.

He stood up abruptly. "Aunt, will you excuse me, please. We


need not discuss the question."

"Is anything the matter? Are you ill?" startled by his look. "I
will send for Dr. Ingram."

"If you would be so good as to attend to your own business,


and not to mine, that is all I ask!" Cyril hardly knew what
he said.

The tension had become too great, and the whole room
went round dizzily. He could not have stood alone, or
walked slowly, but he was able to dash across the hall and
into the study, where he flung himself on the sofa, in an
overpowering whirl of brain and mind, physical giddiness
predominating for the moment over all else.

He had not had a touch of the sensation for years. It


brought back vividly, by the more force of association, his
earliest meeting with Jean. He saw again the square block-
like stones, the rushing water, the swirl of the whole
landscape, the little crouching boy; then he heard Jean's
clear voice and light footsteps, and felt her small resolute
hand clasping his. He had loved Jean from that day onward.

Another scene mixed itself up with the last; again a


stepping-stone scene; only this time Jem, not Jean, came to
the rescue.

Cyril heard his own infantine voice asserting positively, "I


mean to marry Jean some day!"

And Jem's manlier tones advising delay—advising him to


become a man before he spoke; for Jean would never marry
one to whom she could not look up.

"Ten years! Twenty years!" groaned Cyril. "And to have cut


myself off from her—by—this!"

CHAPTER XIII.

BOULEVERSEMENT.

"She's bonny, blooming, straight and tall,


And lang has had my heart in thrall;
And aye it charms my very saul,
The kind love that's in her e'e."
R. BURNS.

CYRIL had not remembered to lock the door, and he became


speedily aware of his mistake. It opened, and a head was
inserted.
"Cyril—?"

No answer; so Miss Devereux walked in, and stood looking


down on the prone figure: some real solicitude mingling
with her dissatisfaction.

"Shall I send for Dr. Ingram?"

"No, thanks. I only wish to be left in peace."

"But, Cyril—! Something must be wrong! If you are not ill,


something must have happened. I can't imagine what has
come over you to-day . . . I daresay, after all, it has to do
with those Trevelyans . . . I almost always find, if you are
out of temper, that Jean is at the bottom of it . . . Of
course, it can't really be that you care so much about that
odious man—Captain Lucas, I mean. Impossible, you know .
. . After all, I really do believe, it is only that something has
disagreed with you. If you will take such violent exercise,
and eat such unwholesome food, what can one expect?
Why, that stew yesterday—my digestion would not stand it
for a moment! I shall tell cook never to send it up again."

Cyril lay motionless on his face through this harangue.

"If you go on so, you are sure to end by having some


attack. People always do. And as for the Lucases, I only
hope you will take warning, and keep clear of them in the
future! It ought to be a lesson to you. An artful, designing
girl, like Miss Lucas—"

Cyril spoke without stirring. "Will you stop that, if you


please! I wish to be alone."

"Well, I must say, I do think you are a very ungrateful


nephew," sighed Sybella, with a different species of pathos
from the pathos of little Emmie.
"I must say, I do think—! When you have always been so
much to me! And, I am sure, the care and thought I have
given—And now, just because—Yes, I am going. I haven't
the least desire to stay where I am not wanted. Not the
very least! I only came to bring you a note. It has been left
at the door—Pearce doesn't know, or else he won't say, by
whom. And I can't imagine who the note can be from. It is a
lady's hand, at least a girl's. It might be a child's. Would
you like me to open and see for you, if you are not well?"

"A note!" Cyril's confused brain had not at once taken in the
sense of the word. It dawned upon him in a flash; and with
a leap he was on his feet, demanding, "Where? Give it to
me!"

The astonished Sybella fell back two paces; curiosity


strongly awakened. She could not but be aware that
something unusual was afloat.

"Where is the note?" he repeated, and Sybella's reluctant


fingers yielded it.

"That is not Jean Trevelyan's handwriting, Cyril. Who can it


be from? You don't correspond with any other young ladies,
I hope!" Her manner implying that Jean was enough and
too much!

The words put Cyril on his guard. One glance revealed to


him that the childish unformed writing was indeed Emmie's.
Within this little Silurian-grey envelope, crookedly directed,
lay his fate—the question of his future life-happiness or life-
misery, once for all decided! So it seemed to Cyril at the
moment, though such apparent decisions do not always
turn out to be permanently decisive. Yet, while feeling thus,
he had the self-control to turn carelessly away, to toss the
note on a side-table, and to walk to the mantelpiece.
"Who is it from, Cyril?"

No answer.

"You know, of course. I see you know. Is anything really the


matter? Anything really wrong? One would think it was a bill
—from your face!" suggested Sybella, recalling stories of
extravagant young men and distressed guardians.

She was not Cyril's guardian now, but her mind was unable
to acquiesce in the change wrought by his coming of age.

"A bad bill perhaps!" she went on—without the slightest


idea what is meant technically by a "bad bill."

She had heard the term, and it recurred conveniently.

"My dear boy, you had much better make a clean breast of
it all. Much better! Far better!" She came near, and laid a
hand on his wrist, with an air of advice and interest. "You
know I would so gladly help."

"Thanks!" Cyril withdrew his arm from her touch—rather


pettishly, it must be confessed, but how could he help it?

He stood upright, holding the mantelpiece; his face


colourless, while a surging like the sound of waves filled his
ears. Nevertheless, he forced his lips into a smile.

"I have no bad bills; and I have plenty of money. My tastes


are not so very extravagant. Much obliged to you all the
same. If you have nothing more to say, perhaps you would
be so kind as to leave me to myself for half-an-hour. I have
—things to do—"

"And I am to understand that you have a secret—and that I


am not to be told!"
"You may understand anything that you choose. It is a
matter of indifference. Only, be so good as to leave me
alone."

Cyril walked across the room, and opened the door.

Sybella had no choice but to go. She complained and


protested; but still she went.

Cyril locked and double-locked the door in her rear. Then he


returned to his former station, close beside the fire.

He stood there, fidgeting a little box of wax matches,


striking one after another with delicate accurate fingers. Not
one was bent or broken. He watched each in turn, burning
itself out, as if his whole soul were intent on the process of
combustion.

Why should he read Emmie's note at once? There was no


hurry. Suspense might be bad; but certainty would, in all
likelihood, be worse. He had a gleam of hope now; and that
little childish note might slay all hope in him for evermore.
He could think of Jean now as not impossibly to be his some
day; but after reading Emmie's answer, he might be
debarred from any such dream.

In a few minutes, all would probably be over—all hope of


Jean! All free thought of Jean!

"I mean to marry Jean some day," he had said at ten years
old and had meant it ever since—till the doubts and
hesitations of the last few months. And now, by a hasty
boyish impulse, he had flung that hope out of his own reach
—perhaps! There was a "perhaps" still, though a very faint
one.
Why should Emmie refuse him? He knew himself to be liked
by her; and doubtless her parents would appreciate the
advantages, which she might be too young to weigh . . .
And if Emmie said "Yes," he would be bound. He would have
in honour to go on. In her position, especially, having once
sought her, how could he ever cast her off? Nay, if he could,
what use? Jean would never have him afterwards.

The rushing sound of waves came back, and Cyril's brain


was in a whirl. He bore it for a few seconds; then suddenly,
he could endure no longer. Waiting became intolerable; and
a burst of impatience drove him to the side-table, where lay
the little note. He would know the worst at once.

As he came to the lamp, opened and read, the surging died


away into stillness, and every trace of dizziness passed
away. Cyril glanced round, with an odd feeling that he had
never seen the chairs and tables so motionless. Then he
read the note again.

He could hardly believe his own eyes. At first, he almost


thought his brain must be playing him false.

Refused—after all!

Emmie "liked him very much, but she was afraid she could
not say she loved him." And so "it would not be right." She
"was very sorry to give him pain," but "it would be best in
the end." The utterances were childishly direct and simple;
no manner of hesitation or incertitude about them. She was
grateful to Cyril, but she would not have him.

"Emmie! You're a brick!" spoke Cyril aloud.

A man does not like to be refused; and notwithstanding


Cyril's relief, notwithstanding the weight lifted from him,
there came for one moment a touch of the "wet-blanket"
sensation. He had not expected himself or his belongings to
be so lightly valued; and self-satisfaction sustained a
wound.

But pride, either wounded or unwounded, could claim only a


small share of his attention. As he read and re-read the
brief sentences, hardly able to credit the fact that he was
free, a great wave of joy swept over him. Jean's face rose
once more, quiet, smiling, no longer sad, no longer
reproachful . . . Cyril had something of the boy in him yet;
not so very surprising at twenty-one. He put his face down
on the high mantelpiece, with a sound not far removed from
a sob—

"My own dear dear dear Jean! Never, never any one but
you!"

Then an unreasoning impulse seized him to rush off there


and then to the Rectory; just to look in upon Jean with his
bodily eyes, now that he knew they were not parted for life
by an ever-widening river . . . Yet could he trust himself?
Would he be betrayed into saying too much? To propose to
one lady within an hour after being refused by another
would be too supremely absurd. Cyril laughed at the idea
and resolved not to go.

He could not rest or stand still, but walked to and fro,


unquiet with very joyousness, as he pictured Jean at the
Brow—Jean at his table—Jean in this study. Emmie's little
face never rose between to blot out Jean's. He only felt
intensely grateful to Emmie, as he realized his escape from
a terrible thraldom, possibly life-long.

He would have to be careful, he knew. If Jean suspected his


late fancy for Emmie—and Cyril was pretty sure she did
suspect it—she would not readily put faith in his present
frame of mind.

The best plan, undoubtedly, for himself and for all parties
concerned, would be to make a thorough break—to get
away from Dulveriford entirely. If he only had had
something definite to go for! Staying on at the Brow would
be awkward in many respects. To cut himself suddenly off
from the Lucases would cause remark; yet to go in and out
as before would be impossible. To begin at once openly
seeking Jean might cause misunderstandings; yet how
could he be in the place and not seek her?

Cyril gave the matter full twenty minutes of serious


thought. Then he unlocked his door, and with feeling of
compunction for Miss Devereux, went to the drawing-room.

Sybella was deeply aggrieved, and in cue for a sulk; but the
sight of her nephew's cheerful face and alert air surprised
her into speech:

"Why! But, Cyril—! Then it couldn't have been bad news?"

"It!"

"I mean your note?"

"My note! No; why should it?—" with perfect sang-froid. "I
came to speak about something very different. I am
thinking of a week or two in Town."

"What for?"

"Picture-galleries—"

"Nonsense, Cyril! You can't impose on people like that!"


"And everything else that's going!"

"If you don't choose to tell me the real reason, you needn't
at least pretend—"

"I shall start to-morrow morning—early express."

"Such an extraordinary thing to decide all in a moment—


and not a word to me—"

"Couldn't publish the fact before I knew it myself. Aunt,


you've not heard, I suppose, whether anything is settled
about Mr. Trevelyan?"

"I thought you were there all yesterday afternoon."

Cyril's joyous indifference was more amazing to Sybella


than his previous irritability.

"At the Rectory! I've not seen Jean for days—not spoken to
her, I mean. Nothing settled yet?"

"Mr. Trevelyan is ordered to Australia. Dr. Ingram wants him


to stay away two years. I believe he starts in a fortnight."

"And Jean—?"

"Jean will be at Dutton Rectory. He can't afford to take her


too. I call it a wild scheme. As likely as not, he will die out
there, all alone—not a soul near—and Jean will never see
him again. But, of course, it is no concern of ours. I only
wish one could hope that the locum tenens would be the
sort of man I could approve of, but of course his views—"

Cyril heard no more, though he was dimly conscious that


Miss Devereux continued talking. She was apt to continue
talking indefinitely so long as anybody was present to listen.
A sudden idea had come to him, of so startling and brilliant
a nature, that it nearly took away his breath. He had
desired something definite to do; and here it was.
Something for Jean too!—There was the charm of the
notion. True, it would mean a long separation. But if all the
while, he were acting for Jean, living for Jean—what then,
though his waiting should grow to the Patriarch's fourteen
years? Cyril felt that they would seem short, for the love
that he bore to Jean. He stood in the centre of the room,
lost in thought, his eyes sparkling with so remarkable a
scintillation that Sybella stared.

"I can't imagine what has come over you to-day," she said.
"You look—"

"Never mind my looks. Aunt, don't stay up for me. I am


going out."

"Again! You have been out the whole day."

"I must see Jean."

"What for? Really, Cyril, it is too absurd. There is something


underneath all this. Something you have not told me. To go
after Jean Trevelyan to-night—Just look at the clock—! And
when you have not been well! I know you were not well, by
the way you left the dining-room after dinner! Something
has disagreed with you, I am quite sure. And if you get a
chill upon that, from the night air—! It is perfectly crazy!
Perfectly mad! As if you could alter things! Dr. Ingram says
Mr. Trevelyan must go; so, of course, he must. He says it is
as much as his life is worth to stay through another winter
in England. Nobody will care for your opinion . . . But
perhaps that note was from Jean, after all—though I don't
see why you should make such a mystery of it. I dare say
she got somebody else to write the address, so that I
should not know the handwriting."

"About the last thing Jean would ever stoop to do! But I
have no note from Jean."

"Well, I don't see, really, what concern we have with their


plans. Why should we interfere? I don't attempt to stand
between you and your friends; but certainly they are not
people who—My dear aunt always highly disapproved of
them . . . Cyril, you have tried me very much this evening—
you really have!—And I am sure I have been most patient!
But there are limits even to—I really do think—I really have
a right—In fact, I positively insist upon knowing what is the
meaning of this extraordinary behaviour."

Cyril looked down on Miss Devereux's agitated features and


twirling hands.

"Very well," he answered, speaking without the least


unkindness; "if you insist, you shall know. As well now as
later. It means—that I am tired of home, tired of
Dulveriford, tired of doing nothing. It means—that if Jean
does not object, I shall go out in the same ship with Mr.
Trevelyan, and take care of him. It means—that when I
come back, if Jean will have me, I shall make her my wife."

For once, Sybella had no words. She could only gaze


blankly, her lips and jaws dropping apart.

Cyril walked to the door, paused, came back, and stooped


to give her a kiss.

"Good-night," he said pleasantly. "Don't be vexed, aunt. If I


have spoken out, it is by your wish. Of course, that about
Jean is in confidence. She may or may not be willing . . .
Meantime you'll have two years' swing at the Brow, to do as
you like—and I'll take care that you have enough money to
carry you on. After that, we must make some other
arrangement. I should like to build you a jolly little house,
outside Dutton—near to St. John's, you know. But there's
plenty of time to think things over. Good-night."

Without waiting for an answer he was gone; and Sybella


was left to her own cogitations.

Jean rose from a low chair beside the drawing-room fire to


greet Cyril. She seemed to have been for once enjoying the
luxury of idleness; and there was a touch of mournful
gravity in the look she turned upon him. It brought to
Cyril's mind the pale reproachful visionary likeness which
had come to him on the marshes, blotting out Emmie's
face.

"It is late for a call; but you will give me a few minutes," he
said. "Will you not?"

"I can spare a few minutes. It is almost bedtime."

"I have just heard something which I didn't know before.


About your father going to Australia for two years. Is it
true?"

"Dr. Ingram advises at least a year and a half. He would


prefer two years. Yes, it was settled days ago."

"And I never heard! But he ought not to go alone."


"He must."

"Is he well enough?"

"No—not if it could be helped. We have no choice."

"Only, if the thing could be managed—surely, he ought to


have a companion. Think, if he were taken worse out there
—alone among strangers—"

"I know! Do you think I don't know?" asked Jean, lifting sad
eyes to his. "Cyril, I didn't expect you to be cruel. Why
should you say it to me? I know all so well, and yet I cannot
go. There are all the expenses of his illness—and the locum
tenens—and his voyage! And I shall cost him almost nothing
in England, living with cousin Chrissie and Jem. Don't you
see?—The thing has to be."

"I'm not speaking unkindly, but because I have a reason."


Cyril moved to a chair nearer Jean, and looked earnestly
into her face. "Jean—I have a plan, and I think it may be a
comfort to you. Will you let me go out with Mr. Trevelyan?
Will you trust him with me—as my charge?"

"You?"

"I mean it. I'm not joking. To-morrow I shall run up to Town
for a few days; and I can get an outfit in no time. There
isn't a grain of difficulty. I'll secure my passage at once in
the same vessel and be ready to start . . . It's the most
delightful thing I ever thought of. I'm sick of the Brow, and
I want something to do, and I've been longing to see more
of the world. The expense is nothing. I'll do my best to
bring him back to you, safe and sound. Will you trust me?"

A thought came swiftly to Jean as she listened. "He has


gone too far with Miss Lucas, and thinks it best to escape!"
Yet she doubted, because of his joyous air; and while the
guess was not so very wide of the mark, Jean was ignorant
of attendant circumstances. She did not know what to
believe, and answered slowly, after some hesitation: "Yes; if
you really wish to go, for your own sake. It would be the
greatest relief—of course—to know that somebody would be
with him."

"For my own sake—and for his—and most of all for your


sake!"

"No, not for mine. But if you seriously think of going to


Australia for your own sake, then I should be only too
thankful if you could be in the same ship with my father."
"Most of all for your sake, Jean!"

Cyril repeated the words emphatically, and it was impossible


to mistake his meaning. No flush came to Jean's pale cheek,
as she replied, "Call it what you like. I shall be very
grateful."

"I don't want gratitude. I want something different. When I


come back—Jean, listen to me—don't turn away! I have no
right to speak now—I know I have not—but when I come
back—"

He had not meant to say this; the words seemed to be


wrenched from him.

"Stop, Cyril! Hush! I must go upstairs."

"Not yet. There's no hurry. I must know about the ship; and
you must listen to me. When I come back, if I have carried
out my trust faithfully—then—"

"No—I am not going to listen."

"You must! You don't know what I want to say."

Jean laid her hand resolutely across Cyril's mouth.

"No—hush—I will not!" she repeated. "You are to say no


more! . . . What of that poor little Miss Lucas? You see—I
know! I dare say you have meant no harm—and you are
doing this kindness to my father, so I must not blame you—
but there cannot be any playing fast and loose. What you
do is for his sake—your sake—anything you like, only not to
do with me!"
Cyril removed her hand from his mouth, and kept it
prisoner. He had merely meant to give her a gentle hint as
to his hopes; but now there seemed to be no choice about
speaking out; now he could not restrain himself. It might be
the last chance for two years or more.

"You needn't be afraid, Jean. I'm not doing what is wrong.


You don't understand how things are, and I want to make
you understand! . . . I've been a fool, and I don't deny it!
She has not suffered—she doesn't care a rap for me! Yes, I
know—for she won't have me . . . I suppose it was a sort of
craze. I did think I wanted her; and I was demented enough
to speak—and then I found out! I shall not forget what it
was—to feel that I had put a barrier between you and me
for life! It was—awful . . . I seem to have lived through ten
years yesterday. Till her answer came, I mean! . . . You see
—I'm hiding nothing from you! And you can think what you
like—despise me, if you like—But if ever I marry, you will be
my wife! You—and nobody else."

"Are you going to keep me much longer?"

"Not if you will stay without being kept. I'm not asking you
to say anything now. It wouldn't be fair. I can't expect you
to believe in me yet. Only, by-and-by, when I come back—
when you find out that I am the same—that I shall always
be the same—don't you think—? No, I'm not asking you to
speak, really! You shall give me an answer in two years. I'm
only telling you how things are . . . You are entirely free—
only, when I come back, Jean, I shall ask you to be mine!
And if you won't—But I can't let myself think of that! Life
wouldn't be life without you! Till then I shall live on hope.
And your face will be with me always—night and day. You'll
think of me sometimes—won't you?"

"You want to know the name of my father's ship," said Jean.


Somehow she could not make her voice quite so prosaic as
she wished, for a strange joy was fluttering at her heart.

"Yes—I'll write it down in my pocket-book." After doing


which, Cyril said in disappointed accents, "Not one word!"

"I thought you were not asking for a word. You inconsistent
boy!" said Jean calmly. She lifted her eyes, dropped
hitherto; and there was in them the old golden shining,
once reserved for Oswald.

It was too much for Cyril's complete self-control. He made a


hasty motion, an impulsive start forward, as if to clasp her
in his arms; but Jean as quickly eluded him, stepping back.

"No! No! Nothing of that sort," she said in an odd restrained


voice. "No nonsense, please. I shall not see you again till
just at last—and then not alone. We are only friends still,
just as we always have been. Both perfectly free. You
understand? If I choose to marry meantime—Or if you
choose to bring home a nice little Colonial wife—"

"Jean, if you say another word—"

"Then—good-bye!" And she vanished.

BOOK IV.

THE UPSHOT OF IT ALL.

"Yet in one respect,


Just one, beloved, I am in nowise changed;
I love you, loved you . . . loved you first and last,
And love you on for ever. Now I know
I loved you always."
E. B. BROWNING.

CHAPTER I.

DUTTON GOSSIP.

"Mrs. Can.—Well, but this may be all a mistake. You


know,
Sir Benjamin, very trifling circumstances often give
rise
to the most injurious tales."
"School for
Scandal."

"ANY of those circulars ready, Jean? No matter if not—but


—"

Jean mutely indicated a pile.


"All done! Thanks! You are a helper worth having. Now can
you undertake the addresses? I have a list somewhere—in
my study."

"My dear Jem!" remonstrated Mrs. Trevelyan. She had her


feet on the fender, and an open story-book on her knee.

"I wonder where we are now," murmured Jean.

Jem looked up, and his grey eyes broke into laughter. When
absorbed in thought, he had a harassed look, too old for his
thirty-five years; but when he smiled, all was transformed;
signs of wear and tear vanished; and hollows were
mysteriously filled up.

"I forgot! Yes, of course—we adjourned here. All right—I


have found the list. Just take the names in order, as they
come."

"Jem, you really have no conscience. Jean has been at work


for you the whole day," drowsily remarked Mrs. Trevelyan.

"Oh, I like it. Not another word, please, mother. Yes, give
me the list."

Jem delayed to scan Jean questioningly, and she met his


gaze with a frank smile.

Two years and a quarter in Dutton Rectory had transmuted


her into a daughter of the house. Mrs. Trevelyan was no
longer "cousin" but "mother"; and Jem was a charming
mixture of pastor, master, and brother.

Jean had developed fast in this new environment. She was


in fuller correspondence with it than with any previous
atmosphere. While not a whit less decisive and practical,
she had become softer, gentler, more gracious. That half of
her which had been assiduously repressed at Dulveriford
Rectory was assiduously cultivated at Dutton Rectory; and
Jean's whole being responded to the cultivation, opening
out like a flower in warm sunshine, after long exposure to
east winds. She was less shy and reserved; her smiles had
learnt to come and go freely; and the old habitual gravity
was replaced by habitual sunshine. This was the real Jean,
never before permitted to expand into her natural outlines.
Dearly as she loved her father, much as she felt the long
separation from him, hardly anything could have occurred
more effectual for the finishing touches needed by her
womanly shape, than such a spell of Dutton Rectory life.

A second long and severe illness, several months past,


through which Mr. Trevelyan had been nursed by Cyril with
a daughter's devotion, had delayed the return of the
travellers beyond the time originally fixed; but now they
were believed to be actually en route for home, coming, for
the sake of the voyage, "by long sea" round the Cape of
Good Hope. Cyril's last letter, written from Melbourne, had
spoken of immediately securing their passage in the
"Spanish Gipsy," expected to start some three weeks or so
later.

Since the receipt of this letter, no news had arrived; and


such an unwonted gap in the correspondence caused much
perplexity. The "Spanish Gipsy" had now been for many
weeks on her way. Whether Mr. Trevelyan and Cyril were on
board remained an open question, though there seemed to
be no substantial reason for doubting the fact.

When they should reach England, Dutton Rectory would


have to part with its "daughter;" no agreeable prospect for
Jem or his mother. Jean had made herself a necessary of
life to them both.
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