Java Networking for Students
Java Networking for Students
by
Amol S. Gaikwad
Lecturer,
Government Polytechnic Gadchiroli
Advanced Java Programming
Unit-IV
Networking Basics
in Java
Welcome!
Are you excited for a fun
learning session?
Unit Outcomes
Use the InetAddress class to know the IP address of the give host name
Use URLConnection classes to read and write data to the specified resources
referred by the given URL
Client/Server
ta
Proxy Servers da
n/
tio
Internet Addressing a
rm r k
nfo w o
i e t
n
Domain Name Service (DNS)
Socket
A socket is one endpoint of a two-way communication link between two programs
running on the network
client
Server network
port (socket) program
program port (socket)
Client machine
Server machine
Socket
Internet Protocol (IP) is a low level protocol that divided data into small packets
and sends them to a device with particular IP address across a network
IP protocol doesn't give the guarantee that your data packets will be send to the
destination or not
Transmission Control Protocol (TCP) is a higher level protocol which gives you
guarantee that your data will be deliver to the destination
TCP protocol combines, sorts and resends the data packets to the destination
User Datagram Protocol (UDP) is also a higher level protocol that directly and
quickly transmit your data
UDP is connectionless and unreliable protocol, it doesn't give guarantee that your
data will reach the destination or not
TCP/IP and OSI model
TCP, UDP
protocols
IP protocol
Socket
TCP/IP protocols delivers data (packets) to particular machine, but which
application will use that data is decided by higher-level protocols and port numbers
Follow the following steps to find list of connections and port numbers in windows
Output
HTTP Protocol
HTTP protocol is used by web browsers and servers for transferring hypertext web
pages and images over the internet
In HTTP protocol when a client requests a file from the server, it prints name of file
in special format to a predefined port number, this is known as hit action
The client also reads back the content (data) of file from the port number
The server responds to the client with a status code - which tells whether client
request for data can be satisfied or not
HTTP Protocol
Server Client
Listens to port 80 Connects to port 80
A client is any device that wants to use the resources provided by the server
The resources provided by the server are always available and client can use it
whenever it requires
A single compute/server can serve many clients at a same time due to concept of
port
A server can accept multiple clients on a same port number, but each client will
have different unique session
po soc
rt ke t 6
client no t e client
network .1 c k o.
so rt n
po
socket socket
port no. 2 port no. 5
et
ck .3 so
so no po ck
r t rt et client
client po server no
.4
client
client
Proxy Servers
A proxy server is a server that acts as a client for some other server
When the client wants some information or web pages from the server then it will
not directly communicate with server
The client will first communicate with proxy server for data, then proxy server will
forward the request to actual server and give back the data to the client
Proxy server can cache (store) the web pages , which can be accessed without going
to the actual server, reducing time, and bandwith
Proxy Servers
2)
pr
ox
ys
3) er
s ve
actual server er rf
ve or
rs wa
en rd
ds sr
da eq
ta ue
to st
pr
ox
ys
er
ve 1) client requests data
r
Internet address (IP address) uniquely identifies each computer on the internet
IP address is divided into two parts - one part specifies the network prefix and the
other part identifies the host identifier
Class B address -
In class B address the first 16 bits is a network part and remaining 16 bits
represent host part of a network
Class D address -
In class D address all the 32 bits are used for network part, no bits are used for
host part
Class D address are called as multicast address and used to uniquely identify
,multicast network, starting address 224.0.0.0
ex: 239.255.255.255
network part ( all 32 bits )
IPv4 Address
Class E address -
Class E addresses have first 4 bit network address set to 1
As IPv4 addresses are limited, IPv6 addresses are introduced which provides more IP
addresses
In future more IPv6 addresses will be used and slowly it will replace IPv4 addresses
IPv4 32 bits
Domain Name Service (DNS)
Domain Name Service (DNS) is a naming system that translates domain name into
numerical IP addresses
192.168.121.133
In same way domain name decribes machine's location from right to left
www.facebook.com
How DNS works ?
Giv
em
eI
Pa
dd
IP res
ad
dr s of 1
es ww
DNS server so w.
fs am
erv az
er on
is 1
2 92
.17
.com
1.1
.12
9
3 1 .1 .129
P 192 .1 7
r ver at I
ne cts se
co n
se rv er
a m az on
ata fro m Client
gets d
Face Down
A5
A4
LTR
4
Ready
Error
Start /
Stop
amazon server
Networking Classes and Interfaces in Java
Java supports both TCP and UDP protocols
Java uses TCP for reliable stream-based I/O across the network
Classes and interfaces used for networking are present in java.net package
ServerSocket URL
Socket URLClassLoader
SocketAddress URLConnection
Networking Classes and Interfaces in Java
The InetAddress class contains both numerical IP address (ex: 192.168.1.5) and
domain name for addresses (ex: www.gpgadchiroli.ac.in)
We interact with this class by using host name rather than IP address
Factory methods are functions which are used for creating objects instead of
directly calling the constructor (without 'new' operator)
InetAddress class
Some of the factory methods are as below :
boolean equals(Object other) - returns true if the current object has same IP
address as other object passes as parameter
String toString( ) - It provides list of host name and IP address in string format
TCP/IP Client Sockets
A socket is one endpoint of a two-way communication link between two programs
running on the network
client
Server network
port (socket) program
program port (socket)
Client machine
Server machine
TCP/IP Client Sockets
TCP/IP sockets provides reliable, bidirectional, persistent, point-to-point stream based
connections between hosts
A socket connects java's I/O system to other program running on local machine or
network machine on the internet
Socket class is used to connect to server sockets and start exchanging protocol
information
int getPort( ) - returns remote port to which this Socket class object was connected
int getLocalPort( ) - returns local port to which this Socket class object was
connected
It is loose collection of higher-level protocols and file formats, all included in a web
browser
We can locate all resources on the web using concept called as 'Uniform Resource
Locator(URL)
The first part of URL is a protocol used (http, gopher,ftp etc) , which is separated
from the remaining URL by colon(:) symbol - in the above example protocol used is
http
The second part of URL is a host name or IP address of a host, separated by double
splashes (//) from left and single slash or colon(:) symbol from right - in the above
example the host name is www.gpgadchiroli.ac.in
How URL works ?
The third part of URL is a port number, which is optional parameter
In the URL the port number is seperated from host name by colon(:) symbol from
left and single slash(/) from right side - in the above example the port number is 80
which is default port number of HTTP protocol
Most HTTP servers will join the file name with the URL - in the above example the
file we want is timetable.pdf or www.gpgadchiroli.ac.in/timetable.pdf
URL class in java
Java has a class called URL which creates and break up urls
URL(URL urlObj, String urlSpecifier) - this constructor creates URL from already
created URL object.
class URLExample
{
public static void main(String args[]) throws MalformedURLException
{
URL obj = new URL("https://gpgadchiroli.ac.in/gpgadchiroli_new/academics/institute-time-table/");
System.out.println("Protocol: "+obj.getProtocol());
System.out.println("Port: "+obj.getPort());
System.out.println("Host: "+obj.getHost());
System.out.println("File: "+obj.getFile());
System.out.println("Ext: "+obj.toExternalForm());
}
}
Output of URL class Program
URLConnection class
URLConnection class is used for getting information about any remote resource
To access the information about URL, we first need to create and object of
URLConnection class using openConnection( ) function
Date
Content-Type
Last-Modified
Content-Length, etc
URL and URLConnection classes are only good for simple programs that connects to
HTTP servers for getting the content
Program of URLConnection class
import java.io.*; System.out.println("Content-Type: "+con.getContentType());
import java.net.*; d = con.getLastModified();
import java.util.Date; if(d==0)
{
class URLConnectionExample System.out.println("Last modified information not available");
{ }
public static void main(String args[]) throws Exception else
{ {
URL obj = new URL("https://www.aicte-india.org/schemes"); System.out.println("Last Modified: "+new Date(d));
URLConnection con = obj.openConnection(); }
long d = con.getDate(); int len = con.getContentLength();
if(d==0) if(len==-1)
{ {
System.out.println("Date not available"); System.out.println("Content length not available");
}
}
else
else
{
{
System.out.println("Date: "+new Date(d));
System.out.println("Content-Length(bytes): "+len);
}
}
}
}
Output of URLConnection class Program
TCP/IP Server Sockets
ServerSocket class is used for creating servers
These servers listens (waits) for local clients or remote clients to connect to the
servers on particular port number
When we create ServerSocket, it will register itself with the operating system
It will tell the operating system that it is interested in connection to the client
maxQueue - the total number of client connection that can remain pending before
server rejects any new connections
ServerSocket(int port) - creates server socket on given port number with deafult
queue length of 50
ServerSocket(int port, int maxQueue) - creates server socket on given port number
with given maxQueue value
When datagrams are send to the receiver there is no guarantee that the receive it
or not
Even when the receiver receives datagrams there is no guarantee that it correct or
damaged
It uses two classes for this - DatagramPacket class which is contains data and
DatagramSocket class which describes process for sending and receiving datagrams
DatagramPacket Class
Some of the constructors of DatagramPacket class are as follow :
DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)
byte[ ] getData( ) - returns byte array of data present in the datagram, it is used to
get the data from the datagram after it is received at destination
int getLength( ) - returns length of valid byte array data in the datagram which is
returned by getData( ) function, it is equal to length of whole byte array
Inet4Address Class and Inet6Address Class
InetAddress class object can refer to both Inet4Address and Inet6Address class
We can simply use InetAddress class to work with both IPv4 and IPv6 addresses
URI Class
URI class contains Uniform Resource Identifiers which are used for identifying the
resources
Server ouput
Simple Client-Server Program Output
Client ouput
Activity Time
Assessment Test
Program Assignment
Group Discussion
Supplemental
Video
https://nptel.ac.in/courses/106/105/1
06105191/
Additional Resources
https://www.tutorialspoint.com/java
https://www.javatpoint.com/free-java-
projects
Summary of Class
1 2 3
Lesson Recap 2
Lesson Recap 1 Lesson Recap 3
AWT/Swing
Delegation components to Adapter
Event Model handle event classes
4
Lesson Recap 4
Inner classes
References
The Complete Reference Java Seventh Edition - Herbert
Schildt,McGraw Hill Publication
Thank You
For Attending!