[go: up one dir, main page]

0% found this document useful (0 votes)
19 views68 pages

Java Networking for Students

java

Uploaded by

findinrafa
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)
19 views68 pages

Java Networking for Students

java

Uploaded by

findinrafa
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/ 68

Advanced Java Programming

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

Develop program for client/server communication through TCP/IP Server sockets


for the given problem

Write a program to illustrate the Client/Server communication using datagram


protocol for the given problem
Basic Concepts in Networking
Networking means communication or exchange of information between two or
more devices/programs/processes over the network or internet

Some basic and important concepts in networking are :

Socket (network socket)

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

A socket has a port number linked with it

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

TCP/IP reserves the lower 1024 ports for specific protocols

Like 21 port number -> FTP protocol


23 port number -> Telnet protocol
25 port number -> email
79 port number -> finger
80 port number -> HTTP protocol
119 port number -> netnews, and so on
How to find list of connections and port numbers in windows ?

Follow the following steps to find list of connections and port numbers in windows

1) Open the command prompt by typing "command prompt" in search


box or by typing "cmd" in run box

2) Type "ipconfig" command in command prompt

3) Then type "netstat -a" command in command prompt to get list of


connections and port numbers
How 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

Accepts the connection Writes


"GET/computer_department.
html
HTTP/1.0\n\n"

Reads upto second end of line (\n)

Sees that GET is a known command


andthat HTTP/1.0 is a valid protocol version

Reads a local file called computer_department.html

Writes "HTTP/1.0 200 OK\n\n" "200" means file is coming


Copies the content of file into socket Reads the content of file and
displays it
Hangs up Hangs up
Client and Server

Servers are hardware/software or combination of both, which has some resources


which can be shared with other computers

Various types of resources are provided by different servers like :

compute servers - provides print servers - provides


computational power collection of printers

disk servers - provides web servers - provides


disk space over network and stores web pages
Client and Server

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 port is socket with particular number on a machine

A server can accept multiple clients on a same port number, but each client will
have different unique session

To handle multiple client connection a server must use multithreaded programming


Client-Server Architecture

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

Proxy server sits between client and actual 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 also filters requests for security

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

4) forwards data to client


client
proxy server
Internet Addressing

Every computer that is connected to an internet has an address, which is called as


IP address

Internet address (IP address) uniquely identifies each computer on the internet

There are to versions of IP protocols :

IPv4 ( Internet IPv6 ( Internet


Protocol, Version 4 ) Protocol, Version 6 )
IPv4 Address

IPv4 address is 32 bit long

IPv4 address is sequence of four numbers,where each number is between 0 to 255,


these four numbers are separated by dot (.) ex: 192.168.1.141

IP address is divided into two parts - one part specifies the network prefix and the
other part identifies the host identifier

There are five classes of IPv4 addresses as follow :

Class A Class B Class C Class D Class E


address address address address address
IPv4 Address
Class A address -
In class A address the first 8 bits or first dotted decimal is a network part and
remaining 24 bits represent host part of a network
There are 128 possible class A networks, starting address is 0.0.0.0
ex: 3.121.152.106
network part (8 bits) host part (24 bits)

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

There are 16384 possible class B networks, starting address is 128.0.0.0


ex: 131.59.121.119
network part (16 bits) host part (16 bits)
IPv4 Address
Class C address -
In class C address the first 24 bits is a network part and remaining 8 bits represent
host part of a network
There are 2097152 possible class C networks, starting address is 192.0.0.0
ex: 192.168.1.144
network part (8 bits) host part (24 bits)

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

The range of class E address is from 240.0.0.0 to 255.255.255.255

Addresses of class E are reserved and it's use is not defined

Addresses 255.255.255.255 is used as broadcast address


ex: 243.161.87.28
IPv6 Address
IPv4 addresses are limited and as more and more devices are getting connected to
the internet, IPv4 addresses are not enough to cover all devices

As IPv4 addresses are limited, IPv6 addresses are introduced which provides more IP
addresses

IPv6 addresses are 128 bits long

In future more IPv6 addresses will be used and slowly it will replace IPv4 addresses

IPv6 is downward compatible with IPv4

IPv6 128 bits

IPv4 32 bits
Domain Name Service (DNS)

It is very difficult to remember numerical IP addresses (ex 192.168.122.167) than


domain names (www.google.co.in)

Domain Name Service (DNS) is a naming system that translates domain name into
numerical IP addresses

Four numbers of IP address describes network heirarchy from left to right

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

UDP is used for more faster point-to-point datagram transfer

Classes and interfaces used for networking are present in java.net package

Following is the list of classes in java.net package

Authenticator DatagramSocketImpl Inet6Address

ContenHandler HttpURLConnection InetSocketAddress

DatagramPacket InetAddress JarURLConnection

DatagramSocket Inet4Address MulticastSocket


Networking Classes and Interfaces in Java

Following is the list of classes in java.net package

NetPermission SocketImpl URLDecoder

NetworkInterface SocketPermission URLEncoder

PasswordAuthentication URI URLStreamHandler

ServerSocket URL

Socket URLClassLoader

SocketAddress URLConnection
Networking Classes and Interfaces in Java

Following is the list of interfaces in java.net package

ContentHandlerFactory SocketImplFactory URLStreamHandlerFactry

FileNameMap SocketOptions DatagramSocketImplFactory


InetAddress class

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

InetAddress class hides the numerical IP address inside

InetAddress class has no visible constructors

For creating objects of InetAddress class Factory methods are used

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 :

static InetAddress getLocalHost( ) throws UnknownHostException - returns an


object of InetAddress class which contains information about local host

static InetAddress getByName(String hostname ) throws


UnknownHostException - returns an object of InetAddress class for a hostname
passed to it

static InetAddress[ ] getAllByName(String hostname ) throws


UnknownHostException - returns an array of all the objects of InetAddress
class which has a particular hostname

static InetAddress getByAddress( ) throws UnknownHostException - this


method takes an IP address and returns an object of InetAddress class for it
InetAddress class
All these methods throws UnknownHostException if they are unable to find the given
hostname

Program of InetAddress class :

import java.io.*; InetAddress obj2 =


import java.net.*; InetAddress.getByName("www.gpgadchiroli.ac.in");
System.out.println(obj2);
class InetAddressExample System.out.println("------------------------------------------");
{ InetAddress obj3[] =
public static void main(String args[]) throws InetAddress.getAllByName("www.google.com");
UnknownHostException for(int i=0;i<obj3.length;i++)
{
{
System.out.println(obj3[i]);
InetAddress obj1 = InetAddress.getLocalHost();
}
System.out.println(obj1); }
System.out.println("------------------------------------------"); }
Output of InetAddress class Program
Instance Methods of InetAddress class
Instance methods are those methods which require that object of its class must be
created before these methods are called

Some functions (instance methods) of InetAddress class are as follow

boolean equals(Object other) - returns true if the current object has same IP
address as other object passes as parameter

byte[ ] getAddress( ) - returns an array of data type byte shows Internet


address in network byte order

String getHostAddress( ) - Returns the host address in InetAddress object in


string format
Instance Methods of InetAddress class

Some functions (instance methods) of InetAddress class are as follow

boolean isMulticastAddress( ) - If the Internet address is multicast then it


returns true otherwise false

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

A socket has a port number linked with it

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

There are two types of TCP sockets as follow :-

server socket client socket


( ServerSocket class) ( Socket class )
TCP/IP Client Sockets
ServerSocket class is like a 'listener' - that waits for client to get connected

Socket class is used to connect to server sockets and start exchanging protocol
information

Socket(String hostName, int port) - this constructor creates a socket connecting


local host with given host named and port number

This constructor can throw UnknownHostException or IOException

Socket(InetAddress ipAddress, int port) - this constructor creates socket from


already existing InetAddess class object and port number

This constructor can throw IOException


TCP/IP Client Sockets
We can get information like port number, IP address etc of a socket by using
following functions

InetAddress getInetAddress( ) - returns InetAddress of a socket

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

InputStream getInputStream( ) - returns InputStream class object linked with the


calling(invoking) socket
TCP/IP Client Sockets

OutputStream getOutputStream( ) - returns the OutputStream class object linked


with the calling(invoking) socket

getChannel( ) - this method returns the channel connected to Socket object


Uniform Resource Locator (URL)
Modern internet today does not use older protocols like - whois, finger, FTP

Today's internet is called as WWW (World Wide Web)

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)

URL uniquely identifies or address information on the internet

Web = All resources identified by URLs + HTML


How URL works ?
A Uniform Resource Locator (URL) is divided into four parts

Consider an example of URL - 'http://www.gpgadchiroli.ac.in/timetable.pdf' or


'http://www.gpgadchiroli.ac.in:80/timetable.pdf'

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

The fourth part of URL is a actual path of file, which we want

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 class has many constructors which are as follow :

URL(String urlSpecifier) - this constructor creates a url in string format and


same url can also be seen in web browser

URL(String protocolName, String hostName, int port, String path) - this


constructor breaks down url into four parts i.e protocol name, host name, port
number and path of file

URL(String protocolName, String hostName, String path) - this constructor breaks


down url into three parts i.e protocol name, host name, and path of file
URL class in java

URL(URL urlObj, String urlSpecifier) - this constructor creates URL from already
created URL object.

Every constructor of URL class throws MalformedURLException

MalformedURLException is thrown when we create a wrong url or url cannot be


found on the net
Program of URL class
import java.io.*;
import java.net.*;

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

The syntax of openConnection( ) function is as below :

URLConnection openConnection( ) - returns an URLConnection object associated


with calling URL object

This function may throw IOException


URLConnection class
When we connect to a remote server we can check the properties of remote object
using URLConnection class, before transporting that object to our local machine

We can get the following information about the remote object :

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

Following are the constructors of ServerSocket class :

maxQueue - the total number of client connection that can remain pending before
server rejects any new connections

The default value of maxQueue is 50


TCP/IP Server Sockets

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

ServerSocket(int port, int maxQueue, InetAddress localAddress) - creates server


socket on given port number with given maxQueue value and the IP address to
which the socket binds given by localAddress

accept( ) - this is a blocking function of ServerSocket class, used to wait for


communication with client and then return an object of Socket class which is used
for communication with client
Datagrams

Datagrams are packets of information passed between machines

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

Java implements datagram by using UDP protocol

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 size)

DatagramPacket(byte data[ ], int offset, int size)

DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)

DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)

Where byte data[ ] = It is a buffer where received data will be stored

int size = size of the packet

int offset = It is offset in the buffer where data will be stored

InetAddress ipAddress = It is address of the target (destination) where


data packet will be sent by DatagramSocket class
DatagramPacket Class
int port = It is port number of the target where data packet will be
sent by DatagramSocket class

Some functions of DatagramPacket class are as follow :

InetAddress getAddress( ) - returns the destination InetAddress, where packet will


be sent

int getPort( ) - returns the port number

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

Inet4Address and Inet6Address classes are subclasses (child) classes of InetAddress


class

Inet4Address class represent IPv4 addresses

Inet6Address class represent IPv6 addresses

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

URIs are simlilar to URLs

URLs are subset of URIs

A URI shows standard way to identify a resource

Whereas a URL also describes how to access (get) that resource


Simple Client-Server Program
Server program :-
import java.net.*; while(!str.equals("stop"))
import java.io.*; {
class ServerExample
str=data_in.readUTF();
{
public static void main(String args[])throws Exception
System.out.println("client message is : "+str);
{ str2=br.readLine();
ServerSocket server_socket = new ServerSocket(3428); data_out.writeUTF(str2);
Socket s = server_socket.accept(); data_out.flush();
DataInputStream data_in = new DataInputStream(s.getInputStream()); }
DataOutputStream data_out = new DataOutputStream(s.getOutputStream());
data_in.close();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s.close();
String str="",str2="";
System.out.println("Server is running..........."); server_socket.close();
}
}
Simple Client-Server Program
Client program :-
import java.net.*; while(!str.equals("stop"))
import java.io.*; {
class ClientExample str = br.readLine();
{ data_out.writeUTF(str);
public static void main(String args[])throws Exception data_out.flush();
{ str2=data_in.readUTF();
Socket s = new Socket("localhost",3428); System.out.println("Server message is : "+str2);
DataInputStream data_in = new DataInputStream(s.getInputStream()); }
DataOutputStream data_out = new DataOutputStream(s.getOutputStream()); data_out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); s.close();
String str="",str2=""; }
System.out.println("Client is running........."); }
Simple Client-Server Program Output

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!

You might also like