You are on page 1of 69

Advanced Java

Chapter 4 Networking Basics


Marks=10
Thought of a Day

2
Course Objective(CO)

 Develop java programs using networking


basics

3
Java Networking
 Java Networking is a concept of connecting
two or more computing devices together so
that we can share resources.

 Java socket programming provides facility to


share data between different computing
devices.
 Advantage of Java Networking
1. sharing resources
2. centralize software management

4
What is socket?

5
Socket Programming

6
Widely used java networking terminologies
 IP Address
 Protocol
 Port Number
 MAC Address
 Connection-oriented and connection-less protocol
 Socket
 IP Address
 IP address is a unique number assigned to a node of a
network e.g. 192.168.0.1 . It is composed of octets that
range from 0 to 255.
 It is a logical address that can be changed.

7
 Protocol
 A protocol is a set of rules basically that is followed for
communication. For example:
 IP, FTP, Telnet, SMTP,POP, TCP etc.
 Port Number
 The port number is used to uniquely identify different
applications. It acts as a communication endpoint between
applications.
 The port number is associated with the IP address for
communication between two applications.
 Port numbers 0 to 1024 are reserved for privileged services
and designated as well-known ports.
 Example:TCP-1,FTP-21H, Telnet-23h, HTTP-80h 8
Port and Socket

9
Thought of a Day
"Peace cannot be kept by force; it can only be achieved
by understanding." — Albert Einstein

This Photo by Unknown Author is licensed under CC BY-SA

10
 MAC Address
 MAC (Media Access Control) Address is a unique identifier
of NIC (Network Interface Controller). A network node can
have multiple NIC but each with unique MAC.
 Connection-oriented and connection-less protocol
 In connection-oriented protocol, acknowledgement is sent by
the receiver. So it is reliable but slow. The example of
connection-oriented protocol is TCP.
 But, in connection-less protocol, acknowledgement is not sent
by the receiver. So it is not reliable but fast. The example of
connection-less protocol is UDP.

11
 Socket
 A socket is an endpoint between two way communication.
 Java classes are
 Socket-client side TCP(Connection-oriented)
 ServerSocket-for server side TCP
 DatagramSocket- for client side UDP(connectionless)
 DatagramPacket –for message transfer UDP

12
Proxy Server

13
Proxy Server
 Proxy server is an intermediary server between client and the internet.
 Proxy servers offers the following basic functionalities:
 Firewall and network data filtering.

 Network connection sharing

 Data caching

 Proxy servers allow to hide, conceal(pack) and make your network id

anonymous by hiding your IP address.


 Purpose of Proxy Servers
 Monitoring and Filtering

 Improving performance

 Translation

 Accessing services anonymously

 Security

14
Client-server Model

An application program is known as a client program, running on


the local machine that requests for a service from an application
program known as a server program, running on the remote
machine.
Example : search for product on Amazon gives you available list 15
Advantages of Client-server networks

 Centralized: Centralized back-up is possible in


client-server networks, i.e., all the data is stored
in a server
 Security:All the shared resources are centrally
administered.
 Performance: The use of the dedicated server
increases the speed of sharing resources. This
increases the performance of the overall
system.
 Scalability: We can increase the number of
clients and servers 

16
Disadvantages of Client-Server Network
 Traffic Congestion is a big problem in
Client/Server networks
 when the server is down, then the client
requests cannot be met

17
Thought of a day

Nature holds the key to our


aesthetic, intellectual,
cognitive and even spiritual
satisfaction.-E.O. Wilson

18
Networking Classes in the JDK

 Pakage needed is java.net


 InetAddress class is used to get IP address
 Java programs can use TCP or UDP to communicate
over the Internet.
 The URL, URLConnection, Socket, and ServerSocket
classes all use TCP to communicate over the network.
 The DatagramPacket, DatagramSocket, and
MulticastSocket classes are for use with UDP.

19
InetAddress Class
 This class provides methods to get the IP of any host name
for example  www.google.com
 Class has no visible constructor
 To create object, we have to use factory method
 These methods are static methods and returns object of class
 A static method in Java is a method that is part of a class
rather than an instance of that class.
 Every instance of a class has access to the method.
 Static methods have access to class variables (static
variables) without using the class's object (instance).
 static method can called directly without an object

20
 Factory methods are:
1. static InetAddress getByName(String host) throws
UnKnownHostException It
returns IP address of given host(URL)
2. static InetAddress getLocalHost() throws
UnknownHostException
It returns IP address of local host
3. Static InetAddress getAllByName(String host) throws
UnKnownHostException
It returns all IP addresses of given host(URL)

21
Brainstorming questions
 Why there is need of separate class when IP addresses
are just numbers?
 Look at the return type of each method. What is
different?
 Why factory methods are static?

22
Program on InetAddress Class
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("osborne.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}

23
Output
Here is the output produced by this program.
(Of course, the output you see may be slightly different.)
Local host/206.148.209.138
osborne.com/198.45.24.162
www.nba.com/64.5.96.214
www.nba.com/64.5.96.216

24
Thought of a Day

25
TCP/IP Socket Class
 Constuctors
Socket(String hostName, int port) throws
UnknownHostException,IOException
Creates a socket connected to the named host and port.
Socket(InetAddress ipAddress, int port) throws
IOException
Creates a socket using a preexisting InetAddress object
and a port.

26
TCP/IP Socket Class Methods
InetAddress getInetAddress( )
Returns the InetAddress associated with the Socket
object. It returns null if the socket is not connected.
int getPort( )
Returns the remote port to which the invoking Socket
object is connected. It returns 0 if the socket is not
connected.
int getLocalPort( )
Returns the local port to which the invoking Socket
object is bound. It returns –1 if the socket is not bound
27
ServerSocket Class Constructors
ServerSocket(int port) throws IOException
Creates server socket on the specified port with a queue length
of 50.
ServerSocket(int port, int maxQueue)throws IOException
Creates a server socket on the specified port with a maximum
queue length of maxQueue.
ServerSocket(int port, int maxQueue,InetAddress
localAddress)throws IOException
Creates a server socket on the specified port with a maximum queue
length of maxQueue.On a multihomed host, localAddress specifies the
IP address to which this socket binds.

28
ServerSocket class methods
public Socket accept()
returns the socket and establish a connection between
server and client.

29
Common Methods in both classes
 public InputStream getInputStream()
returns the InputStream attached with this socket.
 public OutputStream getOutputStream()

returns the OutputStream attached with this socket.


 public synchronized void close()

closes this socket

30
Client-Server Communication

31
Program Server Side
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

32
Program Client Side
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

33
Output

34
Thought of a Day

35
Chat Application-Steps

36
Chat Application-Server side
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
This Photo by Unknown Author is
dout.flush(); licensed under CC BY-SA
}
din.close();
s.close();
ss.close();
}}

37
Chat Application-Client Side
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}

38
Output

39
Thought of a Day

40
Thought of a Day

41
URL class
 URL is Uniform Resource Locator.
 It points to a resource on the World Wide

Web
 Example:

https://mitwpu.edu.in/school-of-polytechnic/
1 2 3
1 1 is protocol

2 2 is host name

3 3 is file name

42
Constructors of Java URL class
 URL(String spec)

 URL(String protocol, String host, int port, String file)

 URL(String protocol, String host, int port, String file,


URLStreamHandler handler)

 URL(String protocol, String host, String file)

43
Methods of URL class

Method Description
public String getProtocol() it returns the protocol of the
URL.
public String getHost() it returns the host name of the
URL.
public String getPort() it returns the Port Number of
the URL. If port is not assigned
it returns -1.
public String getFile() it returns the file name of the
URL.
public String getAuthority() it returns the authority of the
URL.

44
Program
import java.net.*;  
public class URLDemo{  
public static void main(String[] args){  
try{  
URL url=new URL("https://mitwpu.edu.in/school-of-polytechnic/");  
  
System.out.println("Protocol: "+url.getProtocol());  
System.out.println("Host Name: "+url.getHost());  
System.out.println("Port Number: "+url.getPort());  
System.out.println("File Name: "+url.getFile());  
  
}catch(Exception e){System.out.println(e);}  
}  
}  

45
Output
Protocol: https
Host Name: mitwpu.edu.in
Port Number: -1
File Name: school-of-polytechnic

46
Java URLConnection class
 It represents a communication link between
the URL and the application. This class can
be used to read and write data to the
specified resource referred by the URL.
 How to get the object of URLConnection class
 The openConnection() method of URL class
returns the object of URLConnection class.
Syntax:
public URLConnection openConnection()throws IOException{}

47
URLConnection Class Methods
Methods Description
int getContentLength() Returns the size in byte of content associated
with resource.
String getContentType() Returns type of content found in the resource.
If the content is not available, it returns null.

long getDate() Returns the time and date of the response.

long getExpiration() Returns the expiry time and date of the


resource. If the expiry date is unavailable, it
return zero.
long getLastModified() Returns the time and date of the last
modification of the resource.
InputStream getInputStream() throws Returns an InputStream that is linked to the
IOException() resource.
String getRequestProperty(String key) Returns the value of the named general request
property for the given connection.

48
Program for URLConnection class
import java.net.*;
import java.io.*;
import java.util.Date;
import java.lang.*;
public class UMLConDemo
{
    public static void main(String args[]) throws Exception
    {
        int c;
        URL url = new URL("http://www.internic.net/");
        URLConnection urlc = url.openConnection();
        long d = urlc.getDate();
        if(d == 0)
             System.out.println("No date Information.");
        else
             System.out.println("Date: "+new Date(d));
        System.out.println("Content Type: "+urlc.getContentType());
        int len = urlc.getContentLength();
        if(len == -1)
             System.out.println("Content length not available");
        else
             System.out.println("Lenght of the Content: "+len);
        d = urlc.getExpiration();
        if(d==0)
              System.out.println("No expiration information.");
        else
              System.out.println("Expires: " + new Date(d));
     }
}

49
Output
Date: Mon Oct 05 16:31:54 IST 2020
Content Type: text/html; charset=UTF-8
Lenghth of the Content: 173
No expiration information.

50
Thought of a Day

51
Comparison Chart

Difference between TCP and UDP


TCP UDP

Full Name Transmission control protocol User datagram protocol

Data Data can be sent and received Data can only be transmitted

Algorithms for flow control and


Options None
acknowledgment

It can be assured that data will be It cannot be assured that


Trustworthy
received data will be received
Protocols UDP is used by DNS,
TCP is used by HTTP, HTTPs,
DHCP, TFTP, SNMP, RIP,
FTP, SMTP and Telnet.
and VoIP.
Speed Slow Faster

Retransmission possible Not possible


52
TCP & UDP
1. TCP depends on connections while there are no connections in UDP.
2. TCP is heavier because it uses packets to establish connections but
UDP does not need any containers for this purpose and is light
weight.
3. TCP is used more by different websites while UDP is preferred by
apps and games.
4. TCP sends material in the form of streams which do not have any
structure while UDP sends data in the form of messages.
5. Overhead is added to the network in TCP while no overhead is added
in the UDP.
6. It can be assured that data will be received in TCP while there are no
assurances if the data will reach the other side in UDP.

53
DatagramSocket andDatagramPacket
 Java DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
 Usefull for UDP programming

 Datagram is bundle of information

Java DatagramSocket class


 Java DatagramSocket class represents a connection-less

socket for sending and receiving datagram packets.


 A datagram is basically an information but there is no

guarantee of its content, arrival or arrival time.


 Client side programming

54
Questions to you students
 Why overhead will be created in TCP?
 What is difference between stream and message?

55
Constructors of DatagramSocket class
DatagramSocket() throws SocketException:
it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
DatagramSocket(int port) throws SocketException:
it creates a datagram socket and binds it with the
given Port Number.
DatagramSocket(int port, InetAddress address) throws
SocketException:
it creates a datagram socket and binds it with the
specified port number and host address.

56
Thought of a Day

57
Methods
 bind() : Binds this socket to specified address and port number.
 Syntax : public void bind(SocketAddress addr)
 connect() : Connects to the specified address and port. If a
connection cannot be made to the specified remote host, the
calls to send() or receive() would throw PortUnreachable
Exception.
 Syntax :public void connect(InetAddress address, int port)
 Syntax :public void connect(SocketAddress address)
 disconnect() : Disconnects the socket. If the socket is not
connected, then this method has no effect.
 Syntax :public void disconnect()

58
 isBound() : Returns a boolean value indicating whether
this socket is bound or not.
Syntax :public boolean isBound()
 isConnected() : Returns a boolean value indicating
whether this socket is connected or not.
Syntax :public boolean isConnected()

59
 send() : Sends a datagram packet from this socket.
Syntax: public void send(DatagramPacket p)
 Parameters :p : packet to send
 receive() : It is used to receive the packet from a sender.
Syntax : public void receive(DatagramPacket p)
 Parameters : p : datagram packet into which incoming
data is filled

60
 setSOTimeout() : This is used to set the waiting time for
receiving a datagram packet. Once the time specified
expires, java.net.SocketTimeoutException is thrown.
 Syntax : public void setSoTimeout(int timeout)
 getSoTimeout() : Returns the timeout parameter if
specified, or 0 which indicates infinite time
 Syntax public int getSoRimeOut()

61
Java DatagramPacket class
 Java DatagramPacket is a message that
can be sent or received. If you send multiple
packet, it may arrive in any order.
Additionally, packet delivery is not
guaranteed.
 Commonly used Constructors of DatagramPacket class

62
For sending purpose, following constructors are used

Syntax :public DatagramPacket(byte[] buf, int offset,


int length, InetAddress address, int port)
Parameters :buf : byte array, offset : offset into the array
length : length of message to deliver, address : address of destination,
port : port number of destination
Syntax :public DatagramPacket(byte[] buf, int offset,
int length, SocketAddress address)
Syntax :public DatagramPacket(byte[] buf, int length,
InetAddress address,int port) Syntax :public
Syntax:DatagramPacket(byte[] buf, int length,
SocketAddress address)

63
For receiving purpose, following constructors are
used :

Syntax :public DatagramPacket(byte[] buf, int offset,


int length)
Parameters :buf : byte arrayoffset : offset into the array
length : length of message to deliver
Syntax :public DatagramPacket(byte[] buf, int length)
Parameters :buf : byte array,length : length of message to deliver

64
SenderSide Program
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "hello world";
InetAddress ia = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ia, 3000);
ds.send(dp);
ds.close();
}
}
127.0.0.1 is same as localhost

65
ReceiverSide Program
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String strRecv = new String(dp.getData(), 0, dp.getLength());
System.out.println(strRecv);
ds.close();
}
}

66
Output

67
68
Thought of a Day

69

You might also like