Chapter 4 Networking Basics
Chapter 4 Networking Basics
Chapter 4 Networking Basics
2
Course Objective(CO)
3
Java Networking
Java Networking is a concept of connecting
two or more computing devices together so
that we can share resources.
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
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.
Data caching
Improving performance
Translation
Security
14
Client-server Model
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
18
Networking Classes in the JDK
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()
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)
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.
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
Data Data can be sent and received Data can only be transmitted
53
DatagramSocket andDatagramPacket
Java DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
Usefull for UDP 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
63
For receiving purpose, following constructors are
used :
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