AJP Unit 2
AJP Unit 2
NETWORKING
NETWORKING BASICS:
To browse the Web or send an email, your computer must be connected to the Internet. The
Internet is the global network of millions of computers. Your computer can connect to the
Internet through an Internet Service Provider (ISP) using a dialup, DSL, or cable modem, or
through a local area network (LAN). When a computer needs to communicate with another
computer, it needs to know the other computer’s address. An Internet Protocol (IP) address
uniquely identifies the computer on the Internet. An IP address consists of four dotted
decimal numbers between 0 and 255, such as 130.254.204.31. Since it is not easy to
remember so many numbers, they are often mapped to meaningful names called domain
names, such as liang.armstrong.edu. Special servers called Domain Name Servers (DNS) on
the Internet translate host names into IP addresses. When a computer contacts
liang.armstrong.edu, it first asks the DNS to translate this domain name into a numeric IP
address and then sends the request using the IP address. The Internet Protocol is a low-level
protocol for delivering data from one computer to another across the Internet in packets. Two
higher-level protocols used in conjunction with the IP are the Transmission Control Protocol
(TCP) and the User Datagram Protocol (UDP). TCP enables two hosts to establish a
connection and exchange streams of data. TCP guarantees delivery of data and also
guarantees that packets will be delivered in the same order in which they were sent. UDP is a
standard, low-overhead, connectionless, host-to-host protocol that is used over the IP. UDP
allows an application program on one computer to send a datagram to an application program
on another computer. Java supports both stream-based and packet-based communications.
Stream-based communications use TCP for data transmission, whereas packet-based
communications use UDP. Since TCP can detect lost transmissions and resubmit them,
transmissions are lossless and reliable. UDP, in contrast, cannot guarantee lossless
transmission. Stream-based communications are used in most areas of Java programming and
are the focus of this chapter. Packet-based communications are introduced in Supplement
III.P, Networking Using Datagram Protocol
The java.net package of the Java programming language includes various classes that
provide an easy-to-use means to access network resources. The classes covered in the
java.net package are given as follows –
to store resources in ResponseCache. The objects of this class provide an edge for
the OutputStream object to store resource data into the cache.
2. CookieHandler – The CookieHandler class is used in Java to implement a
7. Socket – The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations. The users can implement various
networking actions such as sending, reading data, and closing connections. Each
Socket object built using java.net.Socket class has been connected exactly with 1
remote host; for connecting to another host, a user must create a new socket
object.
connectionless point for sending and receiving packets. Every packet sent from a
datagram socket is individually routed and delivered. It can further be practiced
for transmitting and accepting broadcast information. Datagram Sockets is Java’s
mechanism for providing network communication via UDP instead of TCP.
or system, which serves to preserve the data of its users and computers. It behaves
like a wall between computers and internet users. A Proxy Object represents the
Proxy settings to be applied with a connection.
10.URL – The URL class in Java is the entry point to any available sources on the
The java.net package of the Java programming language includes various interfaces also that
provide an easy-to-use means to access network resources. The interfaces included in the
java.net package are as follows:
1. CookiePolicy – The CookiePolicy interface in the java.net package provides the
cookies. CookieManager combines the cookies to the CookieStore for each HTTP
response and recovers cookies from the CookieStore for each HTTP request.
implements a tool to outline a file name and a MIME type string. FileNameMap
charges a filename map ( known as a mimetable) from a data file.
INetAddress
The server program can use the InetAddress class to obtain the information about the IP
address and host name for the client. The server program can use the InetAddress class to
obtain the information about the IP address and host name for the client.An IP address is an
address having information about how to reach a specific host which is a 32-bit unique
address number having an address space of 2^32. The InetAddress class is a representation of
an IP address. It represents both the 32-bit IPv4 address and the 128-bit IPv6 address. It is the
superclass of Inet6Address and Inet4Address classes. An instance of this class consists of an
IP address and usually a hostname depending on whether hostname resolution was performed
during the creation.
Inet4address and inet6address:
1. IPv4
IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in
the ARPANET in 1983. It is a widely used IP version to differentiate devices on the network
using an addressing scheme. A 32-bit addressing scheme is used to store 232 addresses, that is
more than 4 million addresses.
Features of IPv4:
○ It is a connectionless protocol.
○ It utilises less memory and the addresses can be remembered easily with the class
based addressing scheme.
2. IPv6
IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet
addresses. It provides solutions for the problems present in IPv4. It provides 128-bit address
space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also
identified with the name IPng (Internet Protocol next generation).
Features of IPv6:
TCP/IP sockets are used to implement reliable two-way, persistent, point-to-point streaming
connections between hosts on the Internet. The Java I/O system can use sockets to connect to
other programs on the local system or on other systems on the Internet. It is important to note
that the applet establishes a reverse socket connection to the host on which the applet is
loaded. This restriction exists because it is dangerous for applets loaded through a firewall to
access arbitrary systems. There are two types of TCP sockets in Java.
One for the server and one for the client. The ServerSocket class is designed as a "listener",
waiting for a client to connect before doing anything. So ServerSocket is for servers. The
Socket class is for clients. It is designed to connect to a server socket and initiate a protocol
exchange. This is because client sockets are most commonly used in Java applications.
Creating a Socket object implicitly establishes a connection between the client and server.
There is no method or constructor that explicitly exposes details about setting up this
connection.
Socket defines multiple instance methods. For example, a Socket can always check for
associated address and port information using the following methods:
2. int getPort( ): It returns the remote port to which the invoking Socket object is
connected. It returns 0 if the socket is not connected.
3. int getLocalPort( ): Returns the local port to which the invoking Socket object is
bound. It returns -1 if the socket is not bound.
The following program provides a simple socket example. Opens a connection to a "whois"
port (port 43) of the InterNIC server, sends command-line argument to the socket, and prints
the returned data. The InterNIC will try find the argument by the registered Internet domain
name, and then send back the IP address and contact information for that site
The URL class represents a Uniform Resource Locator, which is a reference to a resource on
the internet. A URL typically includes information such as the protocol (e.g., HTTP, FTP),
hostname, port, path, query parameters, and fragment identifier.
You can create an instance of URL using its constructors or by parsing a URL string.
URLConnection:
The Java HttpURLConnection class is http specific URLConnection. It works for HTTP
protocol only.
By the help of HttpURLConnection class, you can retrieve information of any HTTP URL
such as header information, status code, response code etc.
URI stands for Uniform Resource Identifier. A Uniform Resource Identifier is a sequence of
characters used for identification of a particular resource. It enables for the interaction of the
representation of the resource over the network using specific protocols.
Cookies:
Cookies are small pieces of data that a web server sends to a user's web browser and are
stored locally on the user's device. They are commonly used in web applications to maintain
session state, store user preferences, and track user interactions. Cookies play a crucial role in
enabling stateful interactions on the otherwise stateless HTTP protocol. Here are some key
aspects of cookies:
Creation and Storage: When a user visits a website, the web server can send one or more
cookies as HTTP headers in the response. These cookies are then stored on the user's device
in a cookie jar. Each cookie typically consists of a name, a value, and optional attributes such
as expiration date and domain.
Purpose:
Session Management: Cookies are often used to maintain user sessions. A unique session
identifier is stored in a cookie, allowing the server to recognize and associate subsequent
requests with a specific session.
User Authentication: Cookies can store information related to user authentication, such as a
session token or user credentials.
Personalization: Websites can use cookies to remember user preferences, language settings,
and other customizations.
Tracking and Analytics: Cookies can be used to track user behaviour on a website, which is
commonly used for analytics, advertising, and personalization.
Path: Defines the URL path for which the cookie is valid. A cookie may be limited to a
specific directory or subdirectory on a website.
Expires and Max-Age: Specifies when the cookie should expire. The Expires attribute sets a
specific date and time, while Max-Age sets the cookie's lifespan in seconds from the time of
creation.
Secure: If set, the cookie is only transmitted over secure (HTTPS) connections.
HttpOnly: If set, the cookie is not accessible via JavaScript, enhancing security against
certain types of attacks.
Same-Site Attribute: This attribute is used to control whether cookies should be sent with
cross-origin requests. It helps mitigate cross-site request forgery (CSRF) attacks
Cookie Management: Browsers provide user interfaces to manage cookies, allowing users to
view, edit, and delete stored cookies. Users can often configure their browser settings to
control how cookies are handled.
Server-Side Processing: Web servers process incoming cookies to retrieve session data or
other information. Server-side scripting languages like PHP, Python, and Java can read and
set cookies using HTTP headers.
Privacy Concerns: Cookies have raised privacy concerns because they can be used to track
user behaviour across websites. To address these concerns, browser vendors have
implemented features like SameSite cookie attributes and privacy controls.
TCP/IP Sockets:
In networking, TCP/IP server sockets are a fundamental concept for enabling communication
between computers over the TCP/IP (Transmission Control Protocol/Internet Protocol) suite.
Sockets provide an endpoint for sending and receiving data over a network. Here's an
overview of TCP/IP server sockets:
Server Socket: A server socket is a special type of socket that waits for incoming
client connections. It listens on a specific port and IP address, and when a client
attempts to connect to that address and port, the server socket accepts the connection
and creates a new socket for communication with that client.
● Bind the socket to a specific IP address and port using the bind method.
● Communicate with the client using the new socket (e.g., sending and receiving
data).
Port: Ports are 16-bit unsigned integers used to distinguish different services running
on the same IP address. Common ports are reserved for specific services (e.g., port 80
for HTTP, port 443 for HTTPS).
Listening: A server socket continuously listens for incoming connection requests from
clients. When a client sends a connection request, the server socket accepts it, and a
new socket is created for communication with that client.
Concurrency: To handle multiple client connections concurrently, server applications
often use multithreading or asynchronous programming. Each accepted connection
can be processed in a separate thread or task.
Closing Sockets: It's essential to properly close server sockets and client sockets when
they are no longer needed to release network resources. This ensures that the sockets
and associated ports become available for other processes
Datagram:
Low Overhead: Datagram protocols, like UDP, have lower overhead compared to
connection-oriented protocols like TCP. This makes datagrams suitable for scenarios where
low latency and minimal control information are essential, such as real-time multimedia
streaming and online gaming.
Real-Time Communication: Datagram protocols are often used for real-time applications
like voice and video conferencing, online gaming, and live streaming, where low latency is
more critical than guaranteed delivery.
Network Discovery: Datagram packets can be used for services like network discovery and
broadcasting, where a device needs to announce its presence on a network without
establishing a connection.
Simple Protocols: Simple network protocols that don't require the complexities of
connection-oriented communication, such as time synchronisation or DNS (Domain Name
System) queries, may use datagrams.
Event Handling:
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
It is a mechanism to control the events and to decide what should happen after an event occur.
To handle the events, Java follows the Delegation Event model.
● Source: Events are generated from the source. There are various sources like
buttons, checkboxes, list, menu-item, choice, scrollbar, text components,
windows, etc., to generate events.
● Listeners: Listeners are used for handling the events generated from the source.
Each of these listeners represents interfaces that are responsible for handling
events.
● Event Classes:
○ Event classes are specific to the type of event being handled. For example, for
keyboard events, such as key presses and key releases, the key event classes
are used.
○ Key event classes are part of the java.awt.event package and include
KeyEvent and its subclasses like KeyEvent.KEY_PRESSED and
KeyEvent.KEY_RELEASED.
● Event Sources:
○ Event sources are objects that generate events when specific actions occur.
In the context of key events, components like JFrame, JPanel, or any
component that can receive keyboard input can be event sources.
○ The delegation event model is a design pattern used in Java for event
handling. It involves registering event listeners with event sources.
○ When an event occurs (e.g., a key press), the event source delegates the
handling of the event to the registered event listeners.
○ This model allows for decoupling the event source from the event
handling code.
● Adapter Classes:
○ For key events, the KeyAdapter class from the java.awt.event package is
commonly used. It provides empty implementations of the KeyListener
methods.
● Inner Classes:
○ Inner classes are classes defined within another class. They are often used
for event handling because they have access to the enclosing class's
members and can simplify the code by encapsulating event handling logic.
○ In event handling, you can define inner classes that implement the event
listener interfaces and register them with event sources.