[go: up one dir, main page]

0% found this document useful (0 votes)
17 views16 pages

AJP Unit 2

Uploaded by

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

AJP Unit 2

Uploaded by

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

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

Java Networking classes

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 –

1. CacheRequest – The CacheRequest class is used in java whenever there is a need

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

callback mechanism for securing up an HTTP state management policy


implementation inside the HTTP protocol handler. The HTTP state management
mechanism specifies the mechanism of how to make HTTP requests and
responses.

3. CookieManager – The CookieManager class is used to provide a precise

implementation of CookieHandler. This class separates the storage of cookies


from the policy surrounding accepting and rejecting cookies. A CookieManager
comprises a CookieStore and a CookiePolicy.

4. DatagramPacket – The DatagramPacket class is used to provide a facility for the

connectionless transfer of messages from one system to another. This class


provides tools for the production of datagram packets for connectionless
transmission by applying the datagram socket class.

5. InetAddress – The InetAddress class is used to provide methods to get the IP

address of any hostname. An IP address is expressed by a 32-bit or 128-bit


unsigned number. InetAddress can handle both IPv4 and IPv6 addresses.

6. Server Socket – The ServerSocket class is used for implementing

system-independent implementation of the server-side of a client/server Socket


Connection. The constructor for ServerSocket class throws an exception if it can’t
listen on the specified port. For example – it will throw an exception if the port is
already being used.

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.

8. DatagramSocket – The DatagramSocket class is a network socket that provides a

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.

9. Proxy – A proxy is a changeless object and a kind of tool or method or program

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

internet. A Class URL describes a Uniform Resource Locator, which is a signal to


a “resource” on the World Wide Web. A source can denote a simple file or
directory, or it can indicate a more difficult object, such as a query to a database or
a search engine.

11.URLConnection – The URLConnection class in Java is an abstract class

describing a connection of a resource as defined by a similar URL. The


URLConnection class is used for assisting two distinct yet interrelated purposes.
Firstly it provides control on interaction with a server(especially an HTTP server)
than a URL class. Furthermore, with a URLConnection, a user can verify the
header transferred by the server and can react consequently. A user can also
configure header fields used in client requests using URLConnection.

Java Networking Interfaces

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

classes for implementing various networking applications. It decides which


cookies should be accepted and which should be rejected. In CookiePolicy, there
are three predefined policy implementations, namely ACCEPT_ALL,
ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER.

2. CookieStore – A CookieStore is an interface that describes a storage space for

cookies. CookieManager combines the cookies to the CookieStore for each HTTP
response and recovers cookies from the CookieStore for each HTTP request.

3. FileNameMap – The FileNameMap interface is an uncomplicated interface that

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.

4. SocketOption – The SocketOption interface helps the users to control the

behaviour of sockets. Often, it is essential to develop necessary features in


Sockets. SocketOptions allows the user to set various standard options.

5. SocketImplFactory – The SocketImplFactory interface defines a factory for

SocketImpl instances. It is used by the socket class to create socket


implementations that implement various policies.

6. ProtocolFamily – This interface represents a family of communication protocols.

The ProtocolFamily interface contains a method known as name(), which returns


the name of the protocol family.

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.

○ It also offers video conferencing and libraries.

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:

○ It has stateful and stateless configurations.

○ It provides support for quality of service (QoS).

○ It has a hierarchical addressing and routing infrastructure.

TCP/IP Client Sockets

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.

Here are the two constructors used to create a client socket:

1. Socket(String hostName, int port) throws UnknownHostException, IOException:


Creates a socket connected to the specified host and port.

2. Socket(InetAddress ipAddress, int port) throws IOException: Creates a socket using a


pre-existing InetAddress object and a port.

Socket defines multiple instance methods. For example, a Socket can always check for
associated address and port information using the following methods:

1. InetAddress getInetAddress( ): It returns the InetAddress associated with the Socket


object. It returns null if the socket is not connected.

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.

4. InputStream getInputStream( ) throws IOException: Returns the InputStream


associated with the invoking socket.

5. OutputStream getOutputStream( ) throws IOException: Returns the OutputStream


associated with the invoking socket.

6. connect( ): Allows you to specify a new connection


7. isConnected( ): Returns true if the socket is connected to a server

8. isBound( ): Returns true if the socket is bound to an address

9. isClosed( ): Returns true if the socket is closed.

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

URL (Uniform Resource Locator):

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:

URLConnection is an abstract class that represents a connection to a URL. It provides


methods for reading from and writing to the resource pointed to by the URL.Subclasses of
URLConnection are used for specific protocols, such as HttpURLConnection for HTTP
connections.

Http URL Connection:

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.

The java.net.HttpURLConnection is a subclass of URLConnection class.


URI:

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:

​ Socket: A socket is an endpoint for communication across a computer network. It can


be thought of as a combination of an IP address and a port number. Sockets can be of
two types: server sockets and client 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.

​ Server Socket Creation: To create a server socket in a programming language like


Java or Python, you typically follow these steps:

● Create a socket object (e.g., ServerSocket in Java).

● Bind the socket to a specific IP address and port using the bind method.

● Listen for incoming connections using the listen method.

● Accept incoming connections using the accept method. When a client


connects, this method returns a new socket dedicated to communication with
that client.

● 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).

​ IP Address: The IP address specifies the network location of a device. In server


sockets, you can specify a specific IP address to bind the socket to, or you can bind it
to all available network interfaces using a wildcard address (e.g., 0.0.0.0 or ::).

​ 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:

In networking, a "datagram" refers to a self-contained, independent packet of data sent over a


network using a connectionless protocol, typically the User Datagram Protocol (UDP).
Datagram-based communication is different from connection-oriented communication, such
as Transmission Control Protocol (TCP), in several key ways:

Connectionless: Datagram communication is connectionless, meaning that there is no


establishment of a persistent connection between the sender and receiver before data transfer.
Each datagram is treated as an independent unit, and there is no tracking of the order of
delivery or guaranteed delivery.

Unreliable: Datagram communication, especially over UDP, is considered unreliable. There


is no guarantee that datagrams will reach their destination, and there is no automatic
retransmission of lost or corrupted datagrams. Applications built on datagrams must handle
reliability and error checking themselves if needed.

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.

Stateless: Datagram communication is stateless, meaning that there is no ongoing state or


session information maintained between sender and receiver. Each datagram is treated in
isolation, making it suitable for scenarios where maintaining session state is unnecessary.
Use Cases:

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:

Changing the state of an object is known as an event. For example, clicking on a


button, dragging a mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.

The java.awt.event package can be used to provide various event classes.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener
KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Delegation Event model:

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.

● It has Sources and Listeners.


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.

● Event Listener Interfaces:


○ Event listener interfaces define the methods that need to be implemented
by event listeners to handle specific types of events. In the case of key
events, the KeyListener interface from the java.awt.event package is used.

○ KeyListener includes methods like keyPressed, keyReleased, and keyTyped


that must be implemented to respond to keyboard events.

● Delegation Event Model:

○ 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:

○ Adapter classes are convenience classes that provide empty


implementations of listener interfaces. They are used to avoid the need to
implement all the methods of an interface, especially when you only want
to handle a subset of the events.

○ For key events, the KeyAdapter class from the java.awt.event package is
commonly used. It provides empty implementations of the KeyListener
methods.

○ It helps the programmer to save time by reducing the number of lines in


coding.

● 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.

You might also like