Chapter-6 (Networking)
Chapter-6 (Networking)
By: Joseph W.
1
Outline
Introduction
The java.net Networking Classes and Interfaces
TCP/IP Client Sockets
URL
URLConnection
HttpURLConnection
TCP/IP Server Sockets
Datagrams
java.net.http
5/18/2022 2
Introduction
One of the most important reasons that Java became the premier language for network
programming are the classes defined in the java.net package. They provide a convenient means by
which programmers of all skill levels can access network resources.
At the core of Java’s networking support is the concept of a socket.
A socket identifies an endpoint in a network.
Sockets are at the foundation of modern networking because a socket allows a single computer to
serve many different clients at once, as well as to serve many different types of information.
This is accomplished through the use of a port, which is a numbered socket on a particular
machine.
A server is allowed to accept multiple clients connected to the same port number, although
each session is unique.
Socket communication takes place via a protocol.
5/18/2022 3
Cont.
Internet Protocol (IP) is a low-level routing protocol that breaks data into small packets and sends
them to an address across a network, which does not guarantee to deliver said packets to the
destination.
Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string
together these packets, sorting and retransmitting them as necessary to reliably transmit data.
A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to
support fast, connectionless, unreliable transport of packets.
Once a connection has been established, a higher-level protocol ensues, which is dependent on
which port you are using. TCP/IP reserves the lower 1,024 ports for specific protocols.
For Example: Port number 21 is for FTP; 23 is for Telnet; 25 is for e-mail; 80 is for HTTP; etc.
For example, HTTP is the protocol that web browsers and servers use to transfer hypertext pages
and images.
5/18/2022 4
Cont.
A key component of the Internet is the address. Every computer on the Internet has one. An
Internet address is a number that uniquely identifies each computer on the Net.
Originally, all Internet addresses consisted of 32-bit values, organized as four 8-bit values. This
address type was specified by IPv4 (Internet Protocol, version 4). However, a new addressing
scheme, called IPv6 (Internet Protocol, version 6) has come into play. IPv6 uses a 128-bit value to
represent an address, organized into eight 16-bit chunks.
The main advantage of using IPV6 is that it supports a much larger address space than does IPv4.
Just as the numbers of an IP address describe a network hierarchy, the name of an Internet
address, called its domain name, describes a machine’s location in a name space. For example,
www.google.com is in the COM top-level domain; it is called google, and www identifies the server
for web requests.
An Internet domain name is mapped to an IP address by the Domain Naming Service (DNS). This
enables users to work with domain names, but the Internet operates on IP addresses.
5/18/2022 5
The java.net Networking Classes and Interfaces
Java supports both the TCP and UDP protocol families.
TCP is used for reliable stream-based I/O across the network.
UDP supports a simpler, hence faster, point-to-point datagram-oriented model.
5/18/2022 6
Cont.
The java.net package's interfaces are listed below:
5/18/2022 7
Cont.
InetAddress
The InetAddress class is used to encapsulate both the numerical IP address and the domain
name for that address.
You interact with this class by using the name of an IP host, which is more convenient and
understandable than its IP address.
The InetAddress class hides the number inside.
InetAddress can handle both IPv4 and IPv6 addresses.
The InetAddress class has no visible constructors. To create an InetAddress object, you have to
use one of the available factory methods.
Factory methods are merely a convention whereby static methods in a class return an instance
of that class.
5/18/2022 8
Cont.
Three commonly used InetAddress factory methods are shown here:
static InetAddress getLocalHost( ) throws UnknownHostException
static InetAddress getByName(String hostName) throws UnknownHostException
static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that represents the local host.
The getByName( ) method returns an InetAddress for a host name passed to it.
If these methods are unable to resolve the host name, they throw an UnknownHostException.
The getAllByName( ) factory method returns an array of InetAddresses that represent all of the
addresses that a particular name resolves to.
InetAddress also includes the factory method getByAddress( ), which takes an IP address and
returns an InetAddress object. Either an IPv4 or an IPv6 address can be used.
5/18/2022 9
Cont.
5/18/2022 10
Cont.
The InetAddress class has several other methods, which can be used on the objects returned by
the methods just discussed. Here is a sampling:
5/18/2022 11
Cont.
Java includes support for both IPv4 and IPv6 addresses. Because of this, two subclasses of
InetAddress were created: Inet4Address and Inet6Address.
Inet4Address represents a traditional-style IPv4 address.
Inet6Address encapsulates a newer IPv6 address.
Because they are subclasses of InetAddress, an InetAddress reference can refer to either.
5/18/2022 12
TCP/IP Client Sockets
TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-
based connections between hosts on the Internet.
A socket can be used to connect Java’s I/O system to other programs that may reside either on the
local machine or on any other machine on the Internet, subject to security constraints.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. The
ServerSocket class is designed to be a "listener," which waits for clients to connect before doing
anything.
The Socket class is for clients. It is designed to connect to server sockets and initiate protocol
exchanges.
The creation of a Socket object implicitly establishes a connection between the client and server.
There are no methods or constructors that explicitly expose the details of establishing that
connection. Here are two constructors used to create client sockets:
5/18/2022 13
Cont.
Socket defines several instance methods. For example, a Socket can be examined at any time for
the address and port information associated with it, by use of the following methods:
5/18/2022 14
Cont.
You can gain access to the input and output streams associated with a Socket by use of the
getInputStream( ) and getOuptutStream( ) methods, as shown here. Each can throw an
IOException if the socket has been invalidated by a loss of connection.
Several other methods are available, including connect( ), which allows you to specify a new
connection; isConnected( ), which returns true if the socket is connected to a server; isBound( ),
which returns true if the socket is bound to an address; and isClosed( ), which returns true if the
socket is closed.
To close a socket, call close( ).
Closing a socket also closes the I/O streams associated with the socket.
5/18/2022 15
Cont.
Beginning with JDK 7, Socket also implements AutoCloseable, which means that you can use a
try-with-resources block to manage a socket.
Example:
5/18/2022 16
Cont.
5/18/2022 17
URL
The Web is a loose collection of higher-level protocols and file formats, all unified in a web browser.
One of the most important aspects of the Web is that Tim Berners-Lee devised a scalable way to
locate all of the resources of the Net.
Once you can reliably name anything and everything, it becomes a very powerful paradigm. The
Uniform Resource Locator (URL) does exactly that.
The URL provides a reasonably intelligible form to uniquely identify or address information on the
Internet.
URLs are ubiquitous; every browser uses them to identify information on the Web.
A URL specification is based on four components.
5/18/2022 18
Cont.
1) The first is the protocol to use, separated from the rest of the locator by a colon (:).
o Common protocols are HTTP, FTP, gopher, and file, although these days almost
everything is being done via HTTP (in fact, most browsers will proceed correctly if you
leave off the "http://" from your URL specification).
2) The second component is the host name or IP address of the host to use;
o This is delimited on the left by double slashes (//) and on the right by a slash (/) or
optionally a colon (:).
3) The third component, the port number, is an optional parameter, delimited on the left from the
host name by a colon (:) and on the right by a slash (/).
o (It defaults to port 80, the predefined HTTP port; thus, ":80" is redundant.)
4) The fourth part is the actual file path.
Example: https://www.example.com:80/index.html
5/18/2022 19
Cont.
One commonly used form specifies the URL with a string:
URL(String urlSpecifier) throws MalformedURLException
The next two forms of the constructor allow you to break up the URL into its component parts:
URL(String protocolName, String hostName, int port, String path )
throws MalformedURLException
URL(String protocolName, String hostName, String path)
throws MalformedURLException
Example:
5/18/2022 20
Cont.
5/18/2022 21
Cont.
Output:
Notice that the port is –1; this means that a port was not explicitly set.
Given a URL object, you can retrieve the data associated with it. To access the actual bits or
content information of a URL, create a URLConnection object from it,
5/18/2022 22
Cont.
using its openConnection( ) method, like this:
urlc = url.openConnection()
openConnection( ) has the following general form:
URLConnection openConnection( ) throws IOException
It returns a URLConnection object associated with the invoking URL object. Notice that it may
throw an IOException.
5/18/2022 23
URLConnection
URLConnection is a general-purpose class for accessing the attributes of a remote resource.
Once you make a connection to a remote server, you can use URLConnection to inspect the
properties of the remote object before actually transporting it locally.
URLConnection defines several methods. Here is a sampling:
5/18/2022 24
Cont.
5/18/2022 25
Cont.
Notice that URLConnection defines several methods that handle header information.
A header consists of pairs of keys and values represented as strings.
Example:
5/18/2022 26
Cont.
5/18/2022 27
Cont.
5/18/2022 28
HttpURLConnection
Java provides a subclass of URLConnection that provides support for HTTP connections. This class
is called HttpURLConnection.
You obtain an HttpURLConnection in the same way just shown, by calling openConnection() on a
URL object, but you must cast the result to HttpURLConnection.
Once you have obtained a reference to an HttpURLConnection object, you can use any of the
methods inherited from URLConnection. You can also use any of the several methods defined by
HttpURLConnection. Here is a sampling:
5/18/2022 29
Cont.
5/18/2022 30
Cont.
5/18/2022 31
TCP/IP Server Sockets
As mentioned earlier, Java has a different socket class that must be used for creating server
applications.
The ServerSocket class is used to create servers that listen for either local or remote client
programs to connect to them on published ports.
ServerSockets are quite different from normal Sockets. When you create a ServerSocket, it will
register itself with the system as having an interest in client connections.
The constructors for ServerSocket reflect
o The port number that you want to accept connections on and, optionally,
o How long you want the queue for said port to be.
The queue length tells the system how many client connections it can leave pending before it should
simply refuse connections. The default is 50.
The constructors might throw an IOException under adverse conditions. Here are three of its
constructors:
5/18/2022 32
Cont.
ServerSocket has a method called accept( ), which is a blocking call that will wait for a client to
initiate communications and then return with a normal Socket that is then used for communication
with the client.
5/18/2022 33
Datagrams
TCP/IP-style networking is appropriate for most networking needs. It provides a serialized,
predictable, reliable stream of packet data. This is not without its cost, however.
TCP includes many complicated algorithms for dealing with congestion control on crowded
networks, as well as pessimistic expectations about packet loss. This leads to a somewhat
inefficient way to transport data. Datagrams provide an alternative.
Datagrams are bundles of information passed between machines.
Once the datagram has been released to its intended target, there is no assurance that it will
arrive or even that someone will be there to catch it.
Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in
transit or that whoever sent it is still there to receive a response.
Java implements datagrams on top of the UDP protocol by using two classes:
o the DatagramPacket object is the data container,
o while the DatagramSocket is the mechanism used to send or receive the DatagramPackets.
5/18/2022 34
Cont.
DatagramSocket
DatagramSocket defines four public constructors. They are shown here:
o DatagramSocket( ) throws SocketException
o DatagramSocket(int port) throws SocketException
o DatagramSocket(int port, InetAddress ipAddress) throws SocketException
o DatagramSocket(SocketAddress address) throws SocketException
The first creates a DatagramSocket bound to any unused port on the local computer.
The second creates a DatagramSocket bound to the port specified by port.
The third constructs a DatagramSocket bound to the specified port and InetAddress.
The fourth constructs a DatagramSocket bound to the specified SocketAddress. SocketAddress is an
abstract class that is implemented by the concrete class InetSocketAddress.InetSocketAddress
encapsulates an IP address with a port number.
5/18/2022 35
Cont.
All can throw a SocketException if an error occurs while creating the socket.
DatagramSocket defines many methods. Two of the most important are send( ) and receive( ),
which are shown here:
void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException
The send( ) method sends a packet to the port specified by packet.
The receive() method waits for a packet to be received and returns the result.
DatagramSocket also defines the close( )method, which closes the socket.
DatagramSocket also implements AutoCloseable, which means that a DatagramSocket can be
managed by a try-with-resources block.
Other methods:
5/18/2022 36
Cont.
5/18/2022 37
Cont.
DatagramPacket
DatagramPacket defines several constructors. Four are shown here:
o DatagramPacket(byte data [ ], int size)
o DatagramPacket(byte data [ ], int offset, int size)
o DatagramPacket(byte data [ ], int size, InetAddress ipAddress, int port)
o DatagramPacket(byte data [ ], int offset, int size, InetAddress ipAddress, int port)
The first constructor specifies a buffer that will receive data and the size of a packet. It is used for
receiving data over a DatagramSocket.
The second form allows you to specify an offset into the buffer at which data will be stored.
The third form specifies a target address and port, which are used by a DatagramSocket to
determine where the data in the packet will be sent.
5/18/2022 38
Cont.
The fourth form transmits packets beginning at the specified offset into the data.
Think of the first two forms as building an "in box" and the second two forms as stuffing and
addressing an envelope.
DatagramPacket defines several methods, including those shown here, that give access to the
address and port number of a packet, as well as the raw data and its length:
5/18/2022 39
Cont.
5/18/2022 40
Cont.
5/18/2022 41
Cont.
5/18/2022 42
Cont.
5/18/2022 43
java.net.http
Beginning with JDK 11, a new networking package called java.net.http, in the module
java.net.http, has been added. It provides enhanced, updated networking support for HTTP
clients.
This new API is generally referred to as the HTTP Client API.
In general, the HTTP Client API is designed as a superior alternative to the functionality
provided by HttpURLConnection. It also supports the WebSocket protocol for bidirectional
communication.
5/18/2022 44
Cont.
Beginning with JDK 11, a new networking package called java.net.http, in the module
java.net.http, has been added. It provides enhanced, updated networking support for HTTP
clients.
This new API is generally referred to as the HTTP Client API.
In general, the HTTP Client API is designed as a superior alternative to the functionality
provided by HttpURLConnection. It also supports the WebSocket protocol for bidirectional
communication.
5/18/2022 45
Cont.
HttpClient
HttpClient encapsulates the HTTP request/response mechanism. It supports both synchronous
and asynchronous communication.
Once you have an HttpClient object, you can use it to send requests and obtain responses. Thus, it
is at the foundation of the HTTP Client API.
HttpClient is an abstract class, and instances are not created via a public constructor. Rather, you
will use a factory method to build one.
HttpClient supports builders with the HttpClient.Builder interface, which provides several methods
that let you configure the HttpClient.
To obtain an HttpClient builder, use the newBuilder( ) static method.
Next, call build( ) on the builder. It creates and returns the HttpClient instance. For example, this
creates an HttpClient that uses the default settings.
HttpClient myHC = HttpClient.newBuilder().build();
5/18/2022 46
Cont.
HttpClient.Builder defines a number of methods that let you configure the builder.
Example: By default, redirects are not followed. You can change this by calling followRedirects( ),
passing in the new redirect setting, which must be a value in the HttpClient.Redirect enumeration. It
defines the following values: ALWAYS, NEVER, and NORMAL.
The NORMAL setting causes redirects to be followed unless a redirect is from an HTTPS site to
an HTTP site.
HttpClient.Builder myBuilder =
HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL);
HttpClient myHC = myBuilder.build();
In cases in which the default configuration is sufficient, you can obtain a default HttpClient directly
by calling the newHttpClient( ) method. It is shown here:
static HttpClient newHttpClient( )
5/18/2022 47
Cont.
An HttpClient with a default configuration is returned. For example, this creates a new default
HttpClient:
HttpClient myHC = HttpClient.newHttpClient();
HttpRequest
The HTTP Client API encapsulates requests in the HttpRequest abstract class.
To create an HttpRequest object, you will use a builder. To obtain a builder, call newBuilder( ). It
has these two forms:
static HttpRequest.Builder newBuilder( )
static HttpRequest.Builder newBuilder(URI uri)
HttpRequest.Builder lets you specify various aspects of the request, such as what request method
to use. (The default is GET.) You can also set header information, the URI, and the HTTP version,
among others.
5/18/2022 48
Cont.
You can obtain a string representation of the request method by calling method( ) on the
HttpRequest object.
To actually construct a request, call build( ) on the builder instance.
Once you have an HttpRequest instance, you can use it use it in a call to HttpClient’s send( )
method.
HttpResponse
The HTTP Client API encapsulates a response in an implementation of the HttpResponse
interface.
When a request is sent, an HttpResponse instance is returned that contains the response.
HttpResponse defines several methods that give you access to the information in the response.
Arguably, the most important is body( ).
You can obtain the status code associated with the response by calling statusCode( ).
5/18/2022 49
Cont.
Another method in HttpResponse is headers( ), which obtains the response headers.
The headers associated with the response are encapsulated in an instance of the HttpHeaders
class. It contains various methods that give you access to the headers. Example: map( ), shown
here:
Map<String, List<String>> map( )
Responses are handled by implementations of the HttpResponse.BodyHandler interface. Ex:
5/18/2022 50
Cont.
5/18/2022 51
Cont.
5/18/2022 52
Thank You!!
53