University College of Engineering & Technology for Women Kakatiya University
Networking and Collection frame work
Syllabus:
Networking: Networking API, Inet address, TCP/IP client sockets, URL, URL connection, HttpURL
connection, Cookies, TCP/IP server sockets, Datagrams.
Collections Frame work: Collection Interfaces, Collection Classes: Array Class, Vector Class, Stack Class,
Dictionary class, Hash table Class. accessing using iterators, working with maps, comparators.
Networking:
A computer network is a collection of interconnected devices that share resources and information.
These devices can include computers, servers, printers, and other hardware. Networks allow for the
efficient exchange of data, enabling various applications such as email, file sharing, and internet
browsing.
❖ A network is a collection of different devices that are connected together at different levels
❖ The end devices connected in a network are called as hosts
❖ Many devices like Routers, Wi-Fi Adapters and ethernet jacks are assigned with a unique
Manufacturer address known as MAC
❖ Every host will have a unique identity known as an IP Address
❖ The data can be transferred between two computers through some application programs
❖ A set of rules are defined in networking to transfer data among networking devices which are
known as TCP/IP Model and OSI Model.
1|Page K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
Each and every layer performs specific operations using their respective protocols. The list of protocols
of each layer are given as follows.
Terminology:
Network: A collection of interconnected devices, such as computers, printers, and servers, that can
communicate with each other.
Protocol: A set of rules and standards that define how devices on a network communicate with each
other.
IP Address: A unique numerical identifier assigned to each device on a network, used to identify and
communicate with other devices. Ex: [Link]
Host: a host is any computer or device connected to a network that is capable of sending, receiving,
or providing data, services, or applications. The hosts are identified by a name known as domain name
Ex: [Link].
Local Host: Every computer it self acts as a host and assigned by a default IP address [Link] and
names as localhost.
Remote Host: In the client server architecture, the servers act as remote hosts and they will have a
name and ip address. The name of the remote system is known as its domain name and the IP address
is assigned by Internet service adapter.
Server: A server is a powerful computer or system (hardware or software) that provides centralized
services, data, or resources to other computers, known as clients, over a network.
Client: A client is a hardware device or software program that requests information or services from a
server over a network.
DNS (Domain Name System): A system that translates domain names (such as [Link])
into IP addresses, allowing devices to locate and connect to websites and other network resources.
DHCP (Dynamic Host Configuration Protocol): A protocol that automatically assigns IP addresses and
network configuration settings to devices on a network.
TCP/IP (Transmission Control Protocol/Internet Protocol): A set of protocols used to communicate
over the internet and other networks.
2|Page K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
TCP: TCP stands for Transmission Control Protocol, a core protocol that ensures reliable, ordered, and
error-checked data transmission between devices on a network.
UDP: UDP stands for User Datagram Protocol, a fast, connectionless communication protocol that
transmits data in packets called datagrams without establishing a formal connection or confirming
delivery. It prioritizes speed and efficiency over reliability, making it ideal for real-time applications like
online gaming, video streaming, and VoIP where data loss is tolerable and timely delivery is crucial.
Socket: a socket is the software endpoint for a two-way communication link between applications
running on different devices or on the same device. It acts as a virtual "door" or "interface" that
programs use to send and receive data over a network. A socket's unique address is a combination of
an IP address (for the host) and a port number (for the application).
Port: a port is a virtual endpoint that identifies a specific application or service on a computer, allowing
network traffic to be correctly directed and sorted for different processes. Ports are logical addresses,
represented by 16-bit numbers (0-65535), which, combined with an IP address, complete the
destination information for a data packet, ensuring it reaches the correct application on a device.
The commonly used port numbers.
3|Page K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
Java Networking API: Java Networking builds on fundamental concepts (IP, Port, Protocol, Client-
Server) and provides APIs (InetAddress, URL, Socket, ServerSocket, DatagramSocket) to implement
communication over TCP and UDP.
The [Link] package contains a rich set of classes and interfaces to build network applications. The
common classes in [Link] package are listed as follows.
The [Link] interfaces:
InetAddress:
❖ The InetAddress is a class available in [Link] package
❖ Used to identify machines on network
❖ It resolves hostnames to ip addresses
❖ Use to get the host names of the machines both local and remote.
Example Program:
import [Link].*;
public class InetDemo {
public static void main(String[] args) throws Exception {
//Remote Host
InetAddress ip = [Link]("[Link]");
[Link]("Host Name: " + [Link]());
[Link]("IP Address: " + [Link]());
//Local Host
InetAddress local = [Link]();
[Link]("Local Host: " + [Link]() + " - " + [Link]());
}
4|Page K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
}
Output:
Commonly used methods in InetAddress class:
Factory Methods in InetAddress:
The InetAddress class don’t have any constructors, it uses factory methods to work with InetAddress
class. A factory method is a static method that returns an instance of a class. Instead of using the new
keyword directly in your code, you call the factory method to create objects.
SNO Method Description
01 getLocalHost() Returns IP address of the local machine.
02 getByName(String host) Returns IP of given host name (e.g.,
"[Link]").
03 getAllByName(String host) Returns all IP addresses for a host
04 String getHostName() Returns the host name from an IP.
05 String getHostAddress() Returns IP address in string form.
06 isReachable(int timeout) Checks if the address can be reached.
07 byte[] getAddress() Returns a byte array that represents the
object’s IP address in network byte order.
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.
❖ There are two kinds of TCP sockets in Java, 1. Server Socket and 2. Client Socket
❖ 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.
Creating a client: A client can be created by using Socket class. The Socket class has two
constructors for creating clients as follows
1. Socket client=new Socket(String host_name, int port); this may throws
UnKnownHostException, IOException
2. Socket client=new Socket(InetAddress ipaddress,int port); throws IOException
5|Page K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
Methods of Socket Class:
Sno Method Description
1 InetAddress getInetAddress() Returns the IP address of the remote
2 InetAddress getLocalAddress() Returns the local system ip address
3 Int getPort() Returns the port number of remote system through
which is connected
4 Int getLocalPort() Returns the local port number
5 InputStream getInputStream() Returns input stream to receive data.
6 OutputStream getOutputStream() Returns output stream to send data.
7 boolean isConnected() Returns true if socket is connected.
8 boolean isClosed() Returns true if socket is closed.
9 void close() Closes the socket
Example Program:
import [Link].*;
import [Link].*;
public class ClientDemo {
public static void main(String[] args) {
try {
Socket socket = new Socket("[Link]", 80);
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
[Link]("GET / HTTP/1.1");
[Link]("Host: [Link]");
[Link]("Connection: close");
[Link]();
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
// Close resources
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
6|Page K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
}
}
URL:
The URL (Uniform Resource Locator) class in Java is part of the [Link] package and represents a
pointer to a resource on the World Wide Web. It provides methods to access the various components
of a URL and to read content from the resource.
Syntax: protocol://host:port/path?query#fragment
Example: [Link]
Constructors of URL Class:
1. URL(String Hostname)
2. URL(String protocol, String host, int Port, String File_path)
3. URL(String protocol, String Host, String File_path) Heare port is default port
Methods:
SNO Method Description
1 String getProtocol() Returns the protocol
2 String getHost() Returns the host name
3 Int getPort() Returns the port number
4 String getPath() Returns the file path
5 String getQuery() Returns the query
6 URLConnection Returns the instance of
openConnection() URLConnection
7 InputStream openStream() Opens input stream to read
from URL
Example1: Printing the Host Information
import [Link].*;
import [Link].*;
public class URLHost {
public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
// Read content from URL
[Link]("Protocol: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("File: " + [Link]());
[Link]("Ext:" + [Link]());
}
}
7|Page K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
Example2: read data from a URL
import [Link].*;
import [Link].*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
// Read content from URL
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));
String inputLine;
while ((inputLine = [Link]()) != null) {
[Link](inputLine);
}
[Link]();
}
}
8|Page K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
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. These attributes are exposed by the HTTP protocol
specification and, as such, only make sense for URL objects that are using the HTTP protocol.
Example:
// Demonstrate URLConnection.
import [Link].*;
import [Link].*;
import [Link];
class URLConnectioDemo
{
public static void main(String args[]) throws Exception {
int c;
URL hp = new URL("[Link]
URLConnection hpCon = [Link]();
// get date
long d = [Link]();
if(d==0)
[Link]("No date information.");
9|Page K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
else
[Link]("Date: " + new Date(d));
// get content type
[Link]("Content-Type: " + [Link]());
// get expiration date
d = [Link]();
if(d==0)
[Link]("No expiration information.");
else
[Link]("Expires: " + new Date(d));
// get last-modified date
d = [Link]();
if(d==0)
[Link]("No last-modified information.");
else
[Link]("Last-Modified: " + new Date(d));
// get content length
long len = [Link]();
if(len == -1)
[Link]("Content length unavailable.");
else
[Link]("Content-Length: " + len);
if(len != 0) {
[Link]("=== Content ===");
InputStream input = [Link]();
while (((c = [Link]()) != -1)) {
[Link]((char) c);
}
[Link]();
} else {
[Link]("No content available.");
}
}
}
10 | P a g e K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
HttpURLConnection:
1. It is a sub class of URLConnection Class
2. It provides support for HTTP Connections
3. openConnection() method is used for opening an HTTP Connection
Methods:
Cookies:
Cookies are small pieces of data that a web server sends to a client (usually a web browser) to store
information like session IDs, user preferences, or authentication tokens. When the client makes
subsequent requests to the same server, it sends those cookies back, allowing the server to recognize
the client. Cookies are part of the HTTP header. The class HttpURLConnection class can be used to
manage cookies.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class CookieDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
HttpURLConnection conn = (HttpURLConnection) [Link]();
[Link]("GET");
[Link]([Link]().get("Set-Cookie"));
[Link]();
}
}
11 | P a g e K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
TCP/IP Server Sockets:
In Java the servers are created by using a ServerSocket class and the clients are created by using Socket
class. A ServerSocket class open the specified port number for listening incoming requests and then
process the requests and returns the responses.
The methods of ServerSocket class are as follows
A ServerSocket can maintain queue of clients connected and serves the clients as FIFO order. By
default a ServerSocket class maintains 50 clients in a queue and we can change this also. The
ServerSocket class uses accept() method to listen client requests.
Example:
import [Link].*;
import [Link].*;
public class TCPServer {
public static void main(String[] args) {
int port = 5000;
try (ServerSocket serverSocket = new ServerSocket(port)) {
[Link]("Server started. Waiting for client...");
// Wait for a client connection
Socket socket = [Link]();
[Link]("Client connected: " + [Link]());
// Input and Output streams
BufferedReader input = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter output = new PrintWriter([Link](), true);
String message = [Link]();
[Link]("Received from client: " + message);
[Link]("Hello Client, message received: " + message);
[Link]();
[Link]("Connection closed.");
} catch (IOException e) {
[Link]();
}
}
}
12 | P a g e K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
Datagrams:
A datagram is an independent, self-contained packet of data sent over a network, used in
connectionless communication systems. It contains a header with destination and source information
and a payload with the actual data. Datagrams do not guarantee arrival, order, or delivery time, making
them suitable for applications where real-time delivery and low latency are important.
Package Used: [Link]
Classes Used:
1. DatagramPacket: The data container object
2. DatagramSocket: Provides mechanism to send and receive datagram packets
How a datagram socket is created?
Syntax: DatagramSocket(int port) or DatagramSocket(int port, InetAddress ipaddress)
Example: DatagramSocket ds=new DatagramSocket(5000);
Note: The DatagramSocket class throws SocketException
How to send and receive data using DatagramSocket?
The DatagramSocket class provides two different methods to send and receive data in
networking as follws
1. send(DatagramPacket pkt): To send datagram packet
2. receive(DatagramPacket pkt): to receive Datagram packet
DatagramPacket: A Datagram Packet is the data container which actually travels in network. A
datagram packet can be created using the following syntax
DatagramPacket dp=new DatagramPacket(byte[] data, int size);
Working with Datagram Packets:
The DatagramPacket class provides several methods to handle datagram packets. They are as follows
1. byte[] getData(): Returns the Data of DatagramPacket
2. int getLength(): Returns the size of data
3. void setAddress(InetAddress ipaddress): Sets the IPAddress to which the datagram packet should be
delivered
4. void setdata(byte[] data): Sets the data of a datagram packet
5. void setLength: Sets the length of data
Example Program:
import [Link].*;
class WriteServer {
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception {
int pos=0;
while (true) {
int c = [Link]();
13 | P a g e K. RAJU [Link] – Advanced Java Study Material
University College of Engineering & Technology for Women Kakatiya University
switch (c) {
case -1:
[Link]("Server Quits.");
[Link]();
return;
case '\r':
break;
case '\n':
[Link](new DatagramPacket(buffer,pos,
[Link](),clientPort));
pos=0;
break;
default:
buffer[pos++] = (byte) c;
}
}
}
public static void TheClient() throws Exception {
while(true) {
DatagramPacket p = new DatagramPacket(buffer, [Link]);
[Link](p);
[Link](new String([Link](), 0, [Link]()));
}
}
public static void main(String args[]) throws Exception {
if([Link] == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
} else {
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
Execution: Run the program twice as follows
1. Run As server: C:\> java [Link] 3000
2. Run as Client: C:\> java WriteServer
Now in server type text and press enter to send it.
14 | P a g e K. RAJU [Link] – Advanced Java Study Material