100% found this document useful (3 votes)
11 views

Learning Network Programming with Java 1st Edition Reese Richard M pdf download

The document provides information about the book 'Learning Network Programming with Java' by Richard M. Reese, which focuses on building network-enabled applications using Java. It includes links to download the book and other related Java programming resources. The content covers various topics such as network addressing, NIO support, client/server development, and network security.

Uploaded by

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

Learning Network Programming with Java 1st Edition Reese Richard M pdf download

The document provides information about the book 'Learning Network Programming with Java' by Richard M. Reese, which focuses on building network-enabled applications using Java. It includes links to download the book and other related Java programming resources. The content covers various topics such as network addressing, NIO support, client/server development, and network security.

Uploaded by

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

Learning Network Programming with Java 1st

Edition Reese Richard M download

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

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Learning Java Functional Programming 1st Edition Reese


Richard M

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

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/

EJB 3 1 Cookbook 1st Edition M Reese Richard

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

Learning Java Beginning programming with java for


dummies First Edition John Bach

https://textbookfull.com/product/learning-java-beginning-
programming-with-java-for-dummies-first-edition-john-bach/
Java Network Programming Fourth Edition Harold Elliotte

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

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/

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/

Java for Data Science 1st Edition Reese

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

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/
© 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 ]
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of
Congregationalism in the Court Suburb
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: Congregationalism in the Court Suburb

Author: John Stoughton

Release date: August 18, 2013 [eBook #43494]

Language: English

Credits: Transcribed from the 1883 Hodder and Stoughton


edition by David Price. Many thanks to the Royal
Borough of Kensington and Chelsea Libraries for
allowing their copy to be consulted for this
transcription

*** START OF THE PROJECT GUTENBERG EBOOK


CONGREGATIONALISM IN THE COURT SUBURB ***
Transcribed from the 1883 Hodder and Stoughton edition by David
Price, email [email protected]. Many thanks to the Royal Borough of
Kensington and Chelsea Libraries for allowing their copy to be
consulted for this transcription.

CONGREGATIONALISM
IN THE
COURT SUBURB.

BY

JOHN STOUGHTON, D.D.


Formerly Minister of Kensington Chapel.

London:
HODDER AND STOUGHTON,
27, PATERNOSTER ROW.
MDCCCLXXXIII.

Butler & Tanner,


The Selwood Printing Works,
Frome, and London.
DEDICATION.

THE FOLLOWING

HISTORICAL SKETCH,
PREPARED AT THEIR REQUEST,

Is Gratefully Inscribed
TO THE
PRESENT MINISTER AND DEACONS
OF
KENSINGTON CHAPEL.
INTRODUCTION.

At the commencement of my History, I wish to convey some idea of


what Kensington was at the close of the last century, when the
original Nonconformist Church in that place was formed and
established.
Kensington as a parish must be distinguished from Kensington as a
village or suburb. The boundaries of the parish are still unaltered,
yet what it contained ninety years ago was different, indeed, from
what it contains now. It is startling to read in Lyson’s “Environs,”
published in 1795, the following sentence:—“The parish of
Kensington contains about 1,910 acres of land, about half of which is
pasture meadow, about 360 acres are arable land for corn only,
about 230 in market gardens, about 260 cultivated sometimes for
corn and sometimes for garden crops, and 100 acres of nursery
ground.”
I often think, as I am reading history, what a contrast exists
between its background of natural scenery, and the prospect now
before our eyes on the spot to which the history refers. We should
not know Kensington if we could see it as it was when Hornton
Street Chapel was being built. Then all around was rural. Notting
Hill and the whole way to Paddington—where was the parish
boundary to the north—exhibited fields bordered by hedgerows.
Holland Park, to the west, was a lordly demesne such as you see
now “down in the shires,” and the boundary of the parish in that
direction, at what used to be called Compton Bridge, was marked by
a turnpike gate not long ago removed; beyond it lay a bit of country
landscape before you reached the junction of roads at Hammersmith
Broadway. No great change had then taken place since Addison—
who lived in Kensington—wrote to the Earl of Warwick, saying, “The
business of this is to invite you to a concert of music, which I have
found out in a neighbouring wood. It begins precisely at six in the
evening, and consists of a blackbird, a thrush, a robin redbreast, and
a bullfinch. There is a lark that, by way of overture, sings famously
till she is almost out of hearing.” “The whole is concluded by a
nightingale.” Such were the warblers that broke the silence of
Kensington woods when no screech of the railway whistled in the
wind, and no lumbering omnibuses thundered along the highway.
Indeed, I well remember the nightingales in Holland Park, after the
commencement of my ministry at Hornton Street. Earl’s Court, even
then, was separated from Holland Park gates by a country lane
which began at Pembroke Square. But fifty years before, now ninety
years ago, it was thereabouts all pleasant open country, dotted with
homesteads, paddocks, gardens; whilst at eventide broad green
meadows saw “the lowing herd wind slowly o’er the lea.” Brompton,
included within the parish, extended to the borders of Chelsea,
famous for cosy retreats occupied by merchants and literary men.
Turning from south to east, there opened, under the shadow of the
palace, those gardens which had become famous and much admired
in Queen Anne’s time; and after Hornton Street chapel was built, a
minute of the Board of Green Cloth recorded that an annual pension
of £18 was to be paid to a widow, named Gray, “in consideration of
the loss of her husband, who was accidentally shot while the
keepers were hunting foxes in Kensington Gardens.” [9a]
Lyson tells us that in 1795 there had been new buildings erected,
principally in and near the hamlet of Brompton. “The present
number of houses,” he says, “is about 1,240, of which about 1,150
are inhabited, the remainder are for the most part unfinished.” [9b]
So much for the parish. Now look at the Court suburb; so small in
comparison with the parish, that it may be compared to a shrivelled
kernel in a nutshell. There, in the centre, stood the old Parish
Church, pronounced by Bishop Blomfield the ugliest in the country;
and in Church Street, higher up, the Vicarage was encompassed by a
goodly garden and small park, now covered by rows of houses.
Quaint-looking tenements bordered Church Street a little way.
Campden House and grounds retained a palatial appearance. A row
of brick dwellings, taking us back to the days of the first Georges,
still line Holland Street, and were then in their prime. Hornton
Street looked out, in spring, upon blooming orchards. The road
between Kensington Palace Gate and Holland House was, as it still
is, the main thoroughfare; and I conclude that Phillimore Place,
called by the Prince Regent “Dish-clout Row,” from its tasteless slabs
in front, was then in pristine pride. Kensington Square, though
shorn of the glories it possessed under the first two Georges—when
it boasted of forty coaches, and of lords and ladies occupying the
buildings round it—still presented much quiet respectability; and old
inhabitants, as they passed by the palace gates, could tell of having
heard from their fathers and mothers how one morning there issued
thence “Horse Guards with their trumpets, and a company of heralds
with their tabards, to proclaim, after Queen Anne’s death, George,
by the grace of God, of Great Britain, France, and Ireland, King,
Defender of the Faith.”
All round, the Court suburb was separated from neighbouring
hamlets by a belt of orchards, gardens, and nursery grounds; and
the road between Kensington Gardens and Knightsbridge remained
notorious for its loneliness and perils. Opposite Hyde Park were a
few aristocratic mansions, with spacious lawns, shrubberies, and
gardens bounded by lofty walls; but the road was often in very bad
repair. In the middle of the century, Lord Hervey told his mother it
was impassable, and that in Kensington he lived “in the same
solitude as he should do if cast on a rock in the middle of the
ocean.” [11] Matters might have mended somewhat at the time the
chapel was built, but a good old pew-opener, Mr. Mundy, told me
how he remembered that people at Knightsbridge, bound for
Kensington after dark, would wait till they made a number large
enough to defend themselves against the footpads who infested the
thoroughfare. The old half-way house and the turnpike gate,
symbolical of ancient days, lingered so late as the middle of my own
ministry.
Along that road, and through Kensington suburbs, George III. used
to drive down to Windsor in a lumbering coach with outriders and an
escort. There sat on the box, in grand livery, “a body coachman,” as
he was called. His name was Saunders. To speak of that good man
may seem to be travelling out of my record, but it will be seen that
he played an important part in Kensington Church history. He was a
favourite with His Majesty, and used to put tracts in the pocket of
the coach for his master to read on the way to the Royal Borough.
The latter liked them so well, that he encouraged the servant to
keep the pocket furnished with such publications; and we can fancy
the Queen’s grandfather, in his cocked hat and neat wig, poring over
the pages provided for his entertainment and benefit. The
coachman was a Nonconformist, and when he was staying at
Windsor gathered a few people together in a house which bore the
unattractive name of “Hole in the Wall,” where they held a religious
service, and formed the nucleus of the Independent Church of which
I was pastor for eleven years, part of it as colleague with the
venerable Alexander Redford. It is a curious coincidence that this
worthy coachman may be accounted founder of the two Churches in
which I have laboured the whole of my pastoral life.
He lived part of his time at Kensington, and wished to see a
Nonconformist congregation there. He met with a few people in “a
very humble dwelling,” [12] for religious worship, and out of that
grew the Dissenting Church in Hornton Street.
Kensington Parish Church, between 1762 and 1770, was favoured
with the ministry of the celebrated Dr. Jortin, an author and preacher
of extraordinary reputation; and he was succeeded by Dr. Waller, of
whom I know nothing except that he was killed by the fall of a
chimney during a great hurricane in November, 1795. Then came
the Rev. Richard Omerod. “There was no man, perhaps, who more
eminently possessed the faculty of conciliating all ranks and orders
in a large and populous parish than Mr. Omerod. Nor was this
effected by courtly demeanour or by flattering profession, but by
that honest and amiable simplicity of life and heart, which both
dignify and recommend the Christian minister. To a native purity of
mind and unaffected sanctity of life, he added a calm, gentle, and
unobtrusive manner, which never failed at once to disarm hostility
and to command respect. In his discharge of the complicated duties
of a parish priest he was eminent and exemplary. By the higher
orders he was respected and admired, and by the lower orders he
was venerated and loved; and possessing alike the confidence of
both, he was the channel of communicating the bounty of the one to
relieve the necessities of the other.” [13a] He was vicar from 1795 to
1816.
Dr. Waller was incumbent when the body coachman held his
meetings at Kensington, and Mr. Omerod succeeded Dr. Waller soon
after Hornton Street Chapel was built.
I wish we knew more of that coachman, who deserves to be held in
honour by the congregation of the present day; since it appears that
he not only brought together a nucleus for the Church, but
contributed out of his limited means ten pounds for the erection of a
chapel. [13b]
The earliest document preserved relative to the building I may here
insert, as it indicates the different elements of Nonconformity
blended in the enterprise. Some of the originators, most it would
seem, were Presbyterians, but united with them were Independents
and others.

To the friends of Religious Liberty, Sincere Christianity, and of


Benevolent dispositions, etc.:
We, the undersigned,—of whom some have been educated in
the principles of the Established Church of Scotland, and others
in that class of Dissenters in England whose principles, opinions,
and faith is the most generally consonant to, and founded on,
the Word of God as revealed in the Scriptures of the Old and
New Testament, and on the essential doctrines of Christianity as
professed by both the National Churches of England and
Scotland;—being, therefore, Dissenters from the established
mode of worship in this country, and being situated at a great
distance from any place of worship agreeable to the dictates of
our consciences, we, from pure motives of religion and piety
alone, for conveniency to ourselves and families, and to others
who may be like-minded with us in matters of religion, do
propose, under the favour and blessing of a Divine Providence,
to erect and build a (temple) for the worship of Almighty God in
the parish of Kensington and county of Middlesex.
We profess our religious opinions to be, according to the rites,
form of worship, as well as of the doctrines and discipline
agreed upon in the Confession of Faith, by the Assembly of
Divines at Westminster (so far as the circumstances of our
situation will admit of); we wish to follow their soundness of
faith, purity, and simplicity of worship, as far as we judge them
founded on the Word of God, agreeable to the standard of faith
contained in the Holy Scriptures, the alone unerring guide of
faith and manners.
We therefore invite the serious Christian, the friends and lovers
of Gospel truth, to join with us in this good undertaking to
promote the glory of God, the interests of true religion, and the
eternal happiness of ourselves and fellow-Christians; having
nothing in view but to forward the attainment of these great
objects, we leave the briers, and thorny fields of disputation,
and false philosophy, of factions, politics, and jarring interests of
ambitious men, “that we may lead quiet and peaceable lives in
all godliness and honesty,” as commanded. 1 Timothy ii. 1, 2.

Connected with this document is another, shorter and more general,


stating “that a suitable piece of ground, on a long lease,” had been
secured, on which was to be erected a building, “estimated at
upwards of £900,” which had been already begun, and was then
“carrying on.” The object of this paper was to secure contributions.
The builders’ estimate amounted to £927 15s. 6d. The structure
was at once duly registered, “pursuant to the Act of Toleration in
that case made and provided.” A recommendation of the case is
preserved, signed by several ministers, chiefly Presbyterians, stating
that friends at Kensington, for themselves and neighbours—as there
“was no proper regular place of worship for those who could not
conform with the Established Church—had determined to unite their
efforts towards supplying this defect.”
The dimensions of the edifice were sixty feet by forty inside; but the
ground in length extended to one hundred and nine feet.
I. THE FIRST PASTORATE.
THE REV. JOHN LAKE.

No account is given of the chapel opening; but in October, 1794, an


invitation appears, in the name of “the trustees and subscribers,”
addressed to the Rev. John Lake, M.A., [17] requesting him to take
“the pastoral charge of the congregation,” to which, in the following
month, an answer was returned accepting the charge, and
expressing a hope that the people would receive the Word preached
with meekness and affection, with freedom from prejudice, and with
the simplicity of little children. “Carefully guard,” he says, “against
whatever may engender strife and division. Endeavour to keep the
unity of the spirit in the bond of peace. Live in peace, and may the
God of love and peace be with you.” Mr. Lake, it is believed, was a
Presbyterian clergyman, and on the 1st of March he preached two
discourses suitable to the occasion, which was to unite “several
constant and serious hearers at the new chapel” in “church
communion,” that they might enjoy “religious ordinances.” The tone
of the whole letter is devout and beautiful, and gives a favourable
impression of the writer’s character.
“On Sunday, March 8th, a special meeting was held at the chapel in
the afternoon, of as many as were desirous of joining as members
and communicants at the Lord’s Table, when Mr. Lake attended and
entered into religious conversation with those present, to whom he
also delivered a suitable exhortation. The service was begun and
concluded with prayer, singing, etc.”
“March 30th. The Rev. Mr. Lake, who had accepted the pastoral
office some months ago, removed with his family to Kensington.”
“On Thursday, April 9th (notice having been given from the pulpit
the preceding Lord’s Day), Mr. Lake was set apart and admitted to
the pastoral office in this Church, in the following manner: The Rev.
Mr. Moore began with prayer and reading some suitable portions of
Scripture; then singing; Dr. Hunter prayed; singing; the Rev. Mr.
Smith preached a suitable and excellent sermon from Ezekiel iii. 17–
21; then singing, after which Mr. Rutledge concluded with prayer and
benediction. Several other ministers, besides those who engaged,
were present. The reverend ministers and some of the principal
heads of families afterwards dined together. The service at chapel
was conducted to the general satisfaction of all present.”
“On Friday, April 10th, in the evening, a sermon, preparatory to the
administration of the Lord’s Supper, was preached by the Rev. Mr.
Love, from Exodus iii. 5. A meeting was afterwards held to consult
about the choice of elders, when, after some deliberation, it was
thought proper to postpone the choice to a future opportunity.”
“On Sunday, April 12th, the members enjoyed the long wished for
opportunity of joining as a Christian Church at the table of the Lord.
The Lord’s Supper was dispensed in the chapel for the first time by
the Rev. Mr. Lake, in the following manner: After preaching a
suitable discourse from 1 Corinthians xi. 26, and giving out a Psalm,
he came from the pulpit to the communion table, where a linen cloth
and the elements had been previously laid, the great pew, as well as
three or four of the adjoining pews, were filled with communicants.
After rehearsing the words of institution, with some useful remarks,
Mr. Lake prayed what has been called the consecration prayer; then,
with further address to the communicants, he distributed the
elements of bread and wine. After which, during the singing of a
hymn, he returned to the pulpit, gave an exhortation to those who
had received, and concluded the whole with prayer, benediction, and
a collection, as is usual on such occasions.”
The record of that first communion is very interesting. I have seen
the solemnization of the Holy Supper after different methods: at
Rome, before the high altar of St. Peter’s, amidst lights, flowers, and
incense, with attendant cardinals, and all the pomp and splendour of
a Roman court, and have there witnessed theatrical effects; in
England, within the choir of a Protestant cathedral, I have beheld a
bishop and his clergy administering the eucharist to kneeling
worshippers, and have recognised in the scene much picturesque
beauty. But I must say, that while reading the entry in the
Kensington Church book, illuminated by my own memories of its
communion Sundays during more than thirty years, I have before
me a mode of administration, not only different from those just
indicated, but in simplicity approaching, in my estimation, as near as
possible to the Passover feast in the upper room at Jerusalem. It
adds greatly to the interest of this unpretending record, to recall to
mind contemporary events. The Church was formed, the minister
was ordained, and the Lord’s Supper was administered just at the
period of “the Reign of Terror” in Paris and throughout France; and,
I may add, a different reign of terror in London and Great Britain.
The revolution storm had been breaking in wild fury over our
continental neighbours. Blood had been poured out like water by a
ferocious tribunal of madmen calling themselves patriots. In two
months, out of seven thousand political prisoners, five hundred and
twenty-seven had perished under the guillotine. Neither sex nor
age, neither rank nor obscurity, neither wealth nor indigence had
shielded the most innocent from vengeance. Exiles had swarmed
over to England, and were hiding their poverty and shame in the
country village, the English capital, and the Court suburb. Tales of
change after change had reached our shores, and filled thousands of
hearts with terror. English rulers of that day, terrified by what they
heard, may be really said to have lost their heads, for they adopted
such tyrannical measures for repressing sedition and treason, that
Charles James Fox said in reference to the trials of Muir and Palmer
in Scotland, that if the law enforced there should be brought into
England, it would be high time for “him and his friends to settle their
affairs and retire to some happier clime.” It was just afterwards, and
whilst order on the one side and freedom on the other were in
jeopardy, that the humble fathers and founders of the Church at
Kensington met to choose a pastor and to celebrate the Lord’s
Supper in their new fellowship. “God,” says the forty-sixth Psalm, “is
our refuge and strength, a very present help in trouble. Therefore
will not we fear, though the earth be removed, and though the
mountains be carried into the midst of the sea; though the waters
thereof roar and be troubled, though the mountains shake with the
swelling thereof. There is a river, the streams whereof shall make
glad the city of God.” As political storms roared around, the
Kensington company enjoyed that Divine consolation.
The names of the first communicants are preserved, and in the
course of the year 1795 eight others were added. In 1796 nine
more, in 1797 five, and in 1798 three. One of the earliest members
was a Mrs. Schmae whose husband was living when I went to reside
in Kensington. He was a pious old man, full of faith, hope, and love;
and when I visited him on his death bed, he told me he had been
many years member of Dr. Steinkopf’s Lutheran Church in the Savoy,
and showed me a German Bible he valued, which was given to me
by the family after his death.
The principal persons in the management of affairs at the earliest
period were Messrs. Forsyth, Broadwood, and Grey, all Scotch
Presbyterians. Mr. Broadwood was the famous pianoforte maker.
Mr. Grey was a proprietor of the “Brompton Park Nursery,” spoken of
as famous for plants of all sorts, “which supply most of the nobility
and gentry and gentlemen in England.” John Evelyn visited the
nursery in 1694, with Mr. Waller, who “was in admiration at the store
of plants, and how well the nursery was cultivated.”
Amongst early secular incidents connected with the chapel, was an
attempt made on the part of the parish to include the building in the
poor-rate assessment. This was in 1795. But the trustees resisted
the imposition; and on the case being considered by the magistrates
at Hicks Hall, they decided that the place being supported by
voluntary contributions, could not be justly liable to the parish rate.
Similar attempts were made afterwards, with a similar result.
In 1798 the general monthly prayer meeting of the London
Missionary Society was held at Hornton Street, and the Rev. Dr.
Haweis, it is stated in the Church book, preached from the text,
“Awake, awake, put on strength, O arm of the Lord.” [23a] The entry
deserves special remark. Dr. Haweis was rector of Aldwinkle, in
Northamptonshire, and an intimate friend of the Countess of
Huntingdon. At that period a few Evangelical clergymen were
accustomed to preach in Nonconformist pulpits. The famous John
Berridge, rector of Everton, was of the number; and Fletcher of
Madeley frequently ministered the word of life to Methodist
congregations. Dr. Haweis delivered the first annual sermon on
behalf of the London Missionary Society in Spafields chapel; and on
previous occasions preached in places of worship belonging to the
Countess’s connection. Whether it was owing to that circumstance,
I do not know, but as early as 1767 an unpleasantness arose, which
raised a question as to whether he ought to retain his rectory; and
the Rev. Martin Madan, of the Lock Hospital—who, by the way, is
buried at Kensington—advised him to retain it, a piece of advice
which, we are told, subjected Mr. Madan “to much obloquy.” [23b]
Preaching by clergymen in dissenting chapels was deemed an
irregularity, but some bishops winked at it. Whether or not the
practice be legal became a topic of inquiry a few years ago, and
counsel’s opinion was taken on the subject. My friend Dr. Stanley at
that period expressed a wish to occupy Kensington pulpit before I
resigned the pastorate, and an arrangement for the purpose was
deferred in consequence of a controversy on the general subject,
which arose at the time. Counsel’s opinion proved unfavourable, and
the matter dropped. But I may mention that the Rev. Samuel
Minton, whilst still a Church of England incumbent, preached for me
one Sunday evening not long before counsel gave the opinion to
which reference has been made.
It is interesting to remember that Dr. Haweis was a warm friend to
the London Missionary Society, and that after having offered four
hundred pounds for sending the Gospel to Tahiti, he said: “For many
years I have planned, prayed, and sought for an opening for a
mission among the heathen. My dear Lady Huntingdon has
concurred with me in attempting it.” [24a] And again: “My former
experience has convinced me that only by a general union of all
denominations could a broad basis be laid for a mission.” [24b]
That at so early a period of this history such a service should be held
was an augury for good. It showed that the insignificant band of
Christians worshipping in Hornton Street cherished sympathies so
large that they swept over the world, and offered prayers that the
proclamation of the Gospel might reach the ends of the earth. From
the beginning the Kensington Church associated itself with the
history of missionary trials and missionary success. Disaster at the
antipodes sent a thrill of pain, and success there created a pulsation
of joy amongst the obscure worshippers. Hearts mourned over the
capture of the Duff, and in after years over the massacre of
Tongataboo, the imprisonment and death of Smith in Demerara, the
murder of John Williams on the beach of Eromanga, and the
persecutions of early converts by the Queen of Madagascar. From
time to time the countenances of worshippers have brightened on
the arrival of good tidings from the South Seas, from India, from
China, from Caffreland, from the West Indies. And I mention this
because I believe that much of the prosperity enjoyed by Kensington
Congregationalists is owing to their early and ever since continued
co-operation in missionary work. The keynote of their zeal and joy
was struck at that meeting which it is so gratifying to remember.
Mr. Lake’s ministry at Kensington ceased in 1800 or 1801; and the
only notice I have found of his subsequent history, is that he at
length quitted “the Dissenting interest for a curacy in the Established
Church, where he sustained a respectable and useful character to
the day of his death.” [25]
II. THE SECOND PASTORATE.
THE REV. JOHN CLAYTON.
1801–1804.

“The congregation of Hornton Street Chapel, Kensington, being


deprived of the ministerial labours of the Rev. John Lake, by his
resignation, and remaining destitute of a stated overseer in the Lord
till the month of May, 1801, united in a call soliciting Mr. John
Clayton, assistant to the Rev. John Winter, of Newbury, Berks, to
undertake the office of their pastor.” [28] The invitation was in the
name of “the trustees, church, and subscribers,” and received about
one hundred signatures. Mr. Clayton’s reply is not given, but the
records state that he paid a visit and preached two Sabbaths in the
month of June; and on the second Sabbath of August, 1801, he
entered upon his stated labours.
Mr. Clayton was educated partly at Homerton College, partly at
Edinburgh University; and after the completion of his preparatory
studies he spent a short time at Newbury, as assistant to the Rev.
John Winter. He had only just come of age when he was invited to
the Kensington pastorate. Having won for himself a good report
from the people of the Berkshire town, as one who had done his
work “with the ability of a theologist and the faithfulness of a
minister of Christ,” he was praised by the senior pastor, who wrote to
the young man’s father, saying, “I see that he has now a call to
depart with a prospect of usefulness by preaching the Gospel in
another place. I therefore readily commend him to the Lord, and
the word of His grace, and shall rejoice to hear that all our hopes are
realized among the people of Kensington.”
Mr. Clayton was ordained in Hornton Street Chapel the twenty-first of
October, 1801. The Rev. W. Humphreys, of Hammersmith, delivered
the introductory discourse, and the charge to the minister was given
by his father, the Rev. John Clayton, pastor of the Church assembling
in the ancient Weigh House, not far from the London Monument.
This gentleman, dignified and courtly, had come under the influence
of Lady Huntingdon, and to the time of his death remained attached
to the doctrines dear to the countess. His dissent was of a moderate
type, and he did not share in political views prevalent amongst his
brethren; in that respect his son resembled him. He cultivated
friendships with evangelical clergymen, especially Newton and Cecil.
When I was about to enter college I received from him counsel and
encouragement; and I remember well a discourse which he
preached at Norwich fifty years ago, from the words, “Let us go
again and visit our brethren in every city where we have preached
the word of the Lord, and see how they do.” He had visited the
place forty years before, and now came, he said, to see “how they
did,” and to make inquiries relative to their temporal as well as their
spiritual welfare. “Have you made your wills?” asked the venerable
patriarch, with his thickly powdered head.
“The charge he delivered at Kensington to his son was a most
faithful and solemn exposition of ministerial duties, enforced with
amazing vigour and pungency of expression; indeed at times there
was a trenchant fearlessness of utterance almost amounting to
invective against timeserving, hesitating, cowardly preachers who
kept back the truth or proclaimed smooth things to gratify graceless
spirits.” [29]

“I have not language [he said] of indignant severity sufficiently


strong to express the contemptible cowardice, hypocrisy, and
soul-murdering cruelty of those who adopt an indefinite
phraseology in order (such is the plenitude of their prudence
and moderation) that none may suspend their devotion, but
that a heterogeneous mass of nominal Calvinists and real Arians
and Socinians may be assembled (for united they cannot be) in
one society. Frost unites sticks and stones, moss, leaves, and
weeds; the sun separates them. Into the secret of that frosty
liberality may you, my son, never enter, and to the assembly of
its advocates never be thou united.
“Your testimony is to contain nothing but the truth. Sermons
should not consist in declamation, but be calculated to convey
solid instruction. You must teach, and not trifle away time in
exhibiting fine thoughts or playing upon words. Let not your
testimony be encumbered with what is foreign. Be like Paul,
who could say, ‘Therefore seeing we have this ministry, as we
have obtained mercy, we faint not; but have renounced the
hidden things of dishonesty, not walking in craftiness, nor
handling the word of God deceitfully; by manifestation of the
truth commending ourselves to every man’s conscience in the
sight of God.’
“Your testimony should be borne with zeal, in the heat of which
do not lay aside Christian meekness towards opposers. At the
same time, take care that you do not grow lukewarm and
indifferent under the specious pretext of meekness. An
unfaithful, accommodating pastor, perhaps, applauds himself for
carrying it fair with all sorts of people, whereas this peaceable
kind of preaching, in neither condemning heretics and worldly-
minded persons, nor being condemned by them, is no other
than a sign of his being himself in a state of condemnation and
death. That person betrays the truth who ceases zealously to
defend it, or to oppose its professed adversaries, either from
fear of giving occasion of offence, or through a false love of
peace. The shepherd should not only feed the flocks, but also
drive away the grievous wolves.”
When Mr. Clayton had spent a year and a half in the seclusion of
what was then a rural hamlet, he met with an accident whilst riding
on horseback, an exercise to which he was addicted throughout life.
The accident suspended his work for a while, and during that period
his brother George helped to supply his lack of service. There was
considerable resemblance between the two brothers. Each had a
commanding appearance and a sonorous voice. Both were
accustomed to express themselves in measured, ornate sentences,
the style of which was caught in a measure from their good father,
who loved his sons, and discriminated between them by saying
“John had the best stock of goods, but George had the best shop
window.” The attainments and mental abilities of the elder certainly
were superior to those of the younger; yet perhaps the younger
presented what he had to say in a manner more ingenious and with
even more attractive diction than his brother John. They became, as
they grew older, types of a class at the time large and influential,
chiefly known by their intense and popular evangelical ministrations,
their exemplary discharge of pastoral duties, their zealous support of
catholic institutions for the spread of the Gospel, their gentlemanly
demeanour in society, and their large intercourse with ministers and
people of all denominations.
Let me avail myself of the following reminiscences of Mr. Clayton’s
preaching by my beloved friend, the Rev. J. C. Harrison, who
attended at the Poultry when Mr. Clayton was minister there. They
will, with some slight modification, apply to his preaching at
Kensington.

“He was an admirable preacher. In the course of the year you


were sure to hear all the main doctrines of the Christian faith
clearly explained, or if not formally expounded, thrown into a
fuller light by some practical appeal of which he made them the
foundation. When he took up a book of the New Testament,
like the Acts of the Apostles, and founded on it a series of
discussions, he would draw out the spirit of the narrative with
great fidelity and effect, and would rise not unfrequently into
real eloquence. He was amongst his flock hearing the tale of
their sorrows or their joys, their mental conflicts or their bodily
sufferings, and becoming thereby acquainted with all varieties of
life and experience, all kinds of spiritual disease, all phases of
Christian character: seeking meanwhile how to meet difficulties
and soothe sorrow, and correct morbid feelings, and turn tears
of sadness into smiles of joy, and thus he got together the
materials for portraitures of spiritual character drawn to the life,
and these he wrought into the texture of his Sunday sermon. It
is difficult to imagine the help which such discourses afforded to
all classes of true Christian hearers. He mixed with all sorts and
conditions of men, lawyers, doctors, merchants, tradesmen,
mechanics; and as he was a felicitous and ready converser, he
not only threw out shrewd hints and sparkling sayings for their
advantage, but gained from them a vast amount of information
respecting their mode of life, their opinions and practices, their
weak points and strong points, their gains and losses, their
desperate anxieties and temptations, or their exhilarating
successes; and with these facts from life, in his memory, he
spoke in his sermons, ‘not as one that beateth the air,’ but as
one who had been behind the scenes, and knew whereof he
affirmed. His strokes were not delivered at random, but went
straight to the mark. He could reprove, exhort, advise, comfort,
as if he were himself involved every day in the whirl and wear of
life. True his usual style of speech was rather Johnsonian,
intermingled with forms of expression so entirely his own that
you could only call them Claytonian; but those who knew him
well, found that he talked very much as he preached, in
rhetorically shaped sentences, with a singularly felicitous
peculiarity of phrase coined in his own mind, and occasionally
with a good-humoured subsidence into some pointed
colloquialism which told all the more forcibly from its contrast
with his ordinary mode. They felt, therefore, that what he said
was thoroughly genuine, the utterance of a true man and not at
all of a quack, or as he would have said, of an empiric. But
whether experimental or practical, his sermons were richly and
heartily evangelical, full of the very spirit of the Gospel. As
some of his old-fashioned hearers used to say, ‘You could
always reckon on sixteen ounces to the pound.’”

Mr. Clayton was an exemplary pastor. After he removed to Camomile


Street and the Poultry, he visited his people in a most methodical
way, dividing London into districts, and going from house to house,
week after week, to comfort sorrowing hearts, to share in domestic
joys, to guide the perplexed, and to stimulate the lukewarm; this I
know, and therefore it may be inferred that he looked well after the
few sheep in the Kensington fields, feeding them by day, and
watching over them by night. He used to talk of the large “ring
fence” round his church in the city; the ring fence round his church
in the suburb was small, and hence we may be sure that his pastoral
duties were, during his pastorate at Hornton Street, thoroughly
performed. A gentleman by birth and education, with large
sympathies easily evoked, tears and smiles coming at a moment’s
bidding, apt at telling anecdotes, full of humour if not wit, he was a
companion loved in a circle wider than his own congregation; his
genial friendliness and neighbourly visits helped no doubt to
promote the cause of Evangelical Nonconformity.
A number of minutes occur in the record of affairs, relative to
matters of a temporal kind, during Mr. Clayton’s ministry; but there
are no entries relative to the admission of members or other strictly
religious proceedings. One subject in particular excited the pastor’s
solicitude, namely, that the chapel property should be put in trust,
which accordingly was done; and in connection with this many
discussions arose touching what was needful for discharging
pecuniary liabilities. It is plain from what follows that Mr. Clayton
was not satisfied with “the mixture of temporals with spirituals,” as
he called it; and on Christmas Day, 1804, he publicly assigned
reasons for relinquishing the pastoral office. Various rumours were
afloat, which he briefly contradicted as “untrue,” and then told his
friends that if they were asked “Why has Mr. Clayton left
Kensington?” they were to reply, “That it was his earnest wish to be
nearer the immediate circle of his ministerial connections and
religious friends; that his desire was to be united to a Church whose
members more fully coincided with him in sentiment on several
subjects, more especially on the sacrament of the Lord’s Supper;
and particularly that he might find a place where he might not be
habitually perplexed with secular arrangements, and where he might
in some degree enjoy that tranquillity which he deemed so
necessary in the present state of his health.” “I have the pleasure,”
he added, “to inform you all, that last year this chapel was vested in
the hands of nine trustees, who are engaged to see that no minister
shall ever be settled here who does not preach the gospel agreeably
to the tenets of the Assembly’s Catechism.”
Mr. Biggs, the collector and secretary, also resigned his office, and
Mr. Walker was appointed in his room.
On the 31st of October, 1805, it was resolved, “at a meeting held in
the vestry,” that Mr. Hamilton, of Brighton, should be invited to
become pastor, and an invitation accordingly was drawn up, and
signed by two deacons and between eighty and ninety other
persons.
To the invitation Mr. Hamilton sent a negative reply, addressed to
“the Church of Christ assembling for religious worship in Hornton
Street, Kensington, and the subscribers to that interest.”
Meetings afterwards occurred at intervals for the settlement of
pecuniary affairs, until the month of January, 1807, when by the
direction of “the managers, with the members and subscribers
approving,” the secretary, Mr. Walker, wrote to Mr. Leifchild, a
student at Hoxton Academy, who had occupied Kensington pulpit
with great acceptance, to become minister of the chapel. Mr.
Leifchild replied that he could not leave the Academy before the next
Christmas, nor accept any call before the next midsummer. In
August of the same year a meeting was held at Mr. Broadwood’s
house, and it was resolved to secure Mr. Leifchild not less than £160
per annum, with an addition of whatever the chapel might bring in
above that sum. On the 3rd of January, 1808, the members of the
chapel resolved to invite Mr. Leifchild to the pastorate, and in March
he accepted the invitation.
III. THE THIRD PASTORATE.
THE REV. DR. LEIFCHILD.
1808–1824.

“Before accepting the call to Kensington,” he said, as we learn from


the Memoir by his son, “while returning from a visit to that place, I
heard at the house of a friend that Rowland Hill had announced me
to preach at Surrey Chapel on the following Tuesday evening.” He
went and preached, and was surprised at the risibility of the
audience, which was explained when he heard that Mr. Hill had crept
up into the gallery behind the pulpit, and in his own comical way
expressed assent to one part and dissent from another part of the
discourse. The veteran came into the vestry and asked the young
man to become his curate at Wotton-under-Edge. The latter
declined the overture, when the former replied, “That reminds me of
young men setting up in business before they have served their
apprenticeship.” [37] Just before that evening service, the minister
of Surrey Chapel had written to Mr. Wilson, Treasurer of Hoxton
Academy, saying, “I hear much of a young man of the name of
Leifchild. It was supposed that he was going to settle (a bad word
for a young recruiting spiritual officer) at Kensington; but that there
is a set of formal stupid Presbyterians there, who by no means suit
his taste, and that he is consequently still waiting for the further
directing hand of Providence, to know where he is to go.” [38a] Mr.
Hill was mistaken. John Leifchild did settle at Kensington, and was
ordained there in June, 1808, when Dr. Simpson, his tutor, delivered
the charge. Dr. Simpson, it may be remarked, was a man of singular
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