Learning Network Programming with Java 1st Edition Reese Richard M pdf download
Learning Network Programming with Java 1st Edition Reese Richard M pdf download
https://textbookfull.com/product/learning-network-programming-
with-java-1st-edition-reese-richard-m/
https://textbookfull.com/product/learning-java-functional-
programming-1st-edition-reese-richard-m/
https://textbookfull.com/product/natural-language-processing-
with-java-community-experience-distilled-1st-edition-reese-
richard-m/
https://textbookfull.com/product/ejb-3-1-cookbook-1st-edition-m-
reese-richard/
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/
https://textbookfull.com/product/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-5th-edition-marc-loy/
https://textbookfull.com/product/java-for-data-science-1st-
edition-reese/
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
Richard M Reese
BIRMINGHAM - MUMBAI
© CHB Books
Learning Network Programming with Java
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.
www.packtpub.com
© CHB Books
Credits
Reviewer Proofreader
Daniel MÜHLBACHLER Safis Editing
Technical Editor
Humera Shaikh
Copy Editor
Priyanka Ravi
© CHB Books
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.
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.
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
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
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
[ 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
[ 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
[ 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.
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 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.
[ viii ]
© CHB Books Preface
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."
[ ix ]
© CHB Books
Preface
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."
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.
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.
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.
[ 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.
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
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.
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.
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.
[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.
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.
[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);
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());
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.
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 several buffer classes that support primitive data types, such as character,
integer, and float.
[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:
The URLConnection class hides some of the complexity of accessing HTTP servers.
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:
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.
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
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.
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);
}
[9]
© CHB Books
Getting Started with Network Programming
[ 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.
Language: English
CONGREGATIONALISM
IN THE
COURT SUBURB.
BY
London:
HODDER AND STOUGHTON,
27, PATERNOSTER ROW.
MDCCCLXXXIII.
THE FOLLOWING
HISTORICAL SKETCH,
PREPARED AT THEIR REQUEST,
Is Gratefully Inscribed
TO THE
PRESENT MINISTER AND DEACONS
OF
KENSINGTON CHAPEL.
INTRODUCTION.
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.
textbookfull.com