Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

Advanced Java Programming

Unit 4
Networking Basics

RAISONI GROUP OF INSTITUTIONS


Networking Basics

 Java is practically a synonym for Internet programming.


 Network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are connected to each other via a
network. Java encapsulates classes and interfaces to allow low-level
communication details. 
 The java.net package of the J2SE APIs contains a collection of classes and interfaces
2

that provide the low-level communication details, allowing you to write programs
that focus on solving the problem at hand.

RAISONI GROUP OF INSTITUTIONS


Java.net Package

The java.net package provides support for the two common network protocols −

TCP − TCP stands for Transmission Control Protocol, which allows for reliable

communication between two applications. TCP is typically used over the Internet

Protocol, which is referred to as TCP/IP.


3
UDP − UDP stands for User Datagram Protocol, a connection-less protocol that

allows for packets of data to be transmitted between applications.

RAISONI GROUP OF INSTITUTIONS


Socket

 Socket is the most commonly used term in network programming


 Socket provides the way by which the computers can communicate using
connection oriented or connectionless communication

Definition of Socket:
A socket is basically an endpoint of a two way communication link between two
programs running on the network.
4

It is OS controlled interface through which the applications can send or receive


messages to and fro from another application.

RAISONI GROUP OF INSTITUTIONS


Socket

 A socket is bound to a port number so that the TCP layer can identify the application
that data is destined to be sent to.
 An endpoint is a combination of an IP address and a port number.
5  Socket and ServerSocket classes are used for connection-oriented socket programming 
 DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
 Java.net.Socket class represents the socket.
RAISONI GROUP OF INSTITUTIONS
Client Side Programming
In order to initiate a clients request, you need to follow the below-mentioned steps:
1. Establish a Connection
The very first step is to establish a socket connection. A socket connection implies that
the two machines have information about each other’s network location (IP Address)
and TCP port.
You can create a Socket with the help of a below statement:
Socket socket = new Socket(“127.0.0.1”, 5000)
Here, the first argument represents the IP address of Server.
The second argument represents the TCP Port. (It is a number that represents which
application should run on a server.)
2. Communication
In order to communicate over a socket connection, streams are used for both input and
6
output the data. After establishing a connection and sending the requests, you need to
close the connection.
3. Closing the connection
The socket connection is closed explicitly once the message to the server is sent.

RAISONI GROUP OF INSTITUTIONS


Server Side Programming

Server Side Programming


Basically, the server will instantiate its object and wait for the client request. Once the
client sends the request, the server will communicate back with the response.
In order to code the server-side application, you need two sockets and they are as
follows:
A ServerSocket which waits for the client requests (when a client makes a new
Socket())

7 A plain old socket for communication with the client.


After this, you need to communicate with the client with the response.

RAISONI GROUP OF INSTITUTIONS


URL Class

Java URL class mainly deals with URL(Uniform Resource Locator)

which is used to identify the resources on the internet.

For Example: https://ghrietn.raisoni.net/diploma#dcse

Here,   https: -> Protocol

ghrietn.raisoni.net -> hostname

diploma#dcse - > filename


8

URL Class comprises of various methods to return the URL information of a

particular website.

Let’s now understand various methods of Java URL Class.


RAISONI GROUP OF INSTITUTIONS
Methods Of URL class

PROTOCOL HOST NAME FILENAME

1.getProtocol() : Returns protocol of URL

2.getHost() : Returns hostname(domain name) of the specified URL

3.getPort() : Returns port number of the URL specified


9

4.getFile() : Returns filename of the URL

RAISONI GROUP OF INSTITUTIONS


URL DEMO
//URLDemo.java  
import java.net.*;  
public class URLDemo{  
public static void main(String[] args){  
try{  
URL url=new URL("https://ghrietn.raisoni.net/diploma#dcse");  
  
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());  
  
10
}catch(Exception e){System.out.println(e);}  
}  
}  

RAISONI GROUP OF INSTITUTIONS


MCQ on URL
1. What is the first part of URL address?

A. Host name.
B. B. Port number.
C. File path.
D. Protocol.

2. In the format for defining the URL what is the last part?

E. Protocol.
F. File path.
G. Port number.
H. Host name.
11
3. What does URL stands for?
a) Uniform Resource Locator
b) Uniform Resource Latch
c) Universal Resource Locator
d) Universal Resource Latch
RAISONI GROUP OF INSTITUTIONS
MCQ on URL
What will be the output of the following Java code?
1.import java.net.*;
2.class networking
3.{
4.public static void main(String[] args) throws MalformedURLException
5.{
6.URL obj = new URL("https://www.example.com/javamcq");
7.System.out.print(obj.getProtocol());
8.}
9.}

a) http
12
b) https
c) www
d) com

RAISONI GROUP OF INSTITUTIONS


MCQ on URL

What will be the output of the following Java program?


1.import java.net.*;
2.class networking
3.{
4.public static void main(String[] args) throws MalformedURLException
5.{
6.URL obj = new URL("https://www.example.com/javamcq");
7.System.out.print(obj.getPort());
8.}
9.}

13
a) 1
b) 0
c) -1
d) garbage value

RAISONI GROUP OF INSTITUTIONS


URL Connection Class

 It represents communication link between URL and its application


 It can be used to read/write data to the specified resource referred by URL
There are mainly two subclass that extends the URLConnection class-
HttpURLConnection: If we are connecting to any url which uses “http” as its protocol,
then HttpURLConnection class is used.
JarURLConnection: If however, we are trying to establish a connection to a jar file on
the web, then JarURLConnection is used.
Once the connection is established and we have a URLConnection object, we can use it
14

to read or write or get further information about when was the page/file last modified,
content length etc.

RAISONI GROUP OF INSTITUTIONS


Methods Of URL Connection class
 URLConnection openConnection(): opens the connection to the specified URL.
 Object getContent(): retrieves the content of the URLConnection.
 Map<String,List> getHeaderFields(): returns the map containing the values of various header
fields in the http header.
 getContentEncoding(): Returns the value of the content-encoding header field.
 getContentLength(): returns the length of the content header field.
 getDate(): returns value of date in header field.
 getHeaderField(int i): returns the value of ith index of header.
 getHeaderField(String field): returns the value of field named “field” in header
OutputStream getOutputStream(): returns the output stream to this connection.
 InputStream getInputStream(): returns the input stream to this open connection.
 setAllowUserInteraction(boolean): Setting this true means a user can interact with the page.
Default value is true.
15  setDefaultUseCaches(boolean): Sets the default value of useCache field as the given value.
 setDoInput(boolean): sets if the user is allowed to take input or not.
 setDoOutput(boolean): sets if the user is allowed to write on the page. Default value is false since
most of the url dont allow to write.

RAISONI GROUP OF INSTITUTIONS


URL Connection Example
1.import java.io.*;  
2.import java.net.*;  
3.public class URLConnectionExample {  
4.public static void main(String[] args){  
5.try{  
6.URL url=new URL("http://www.javatpoint.com/java-tutorial");  
7.URLConnection urlcon=url.openConnection();  
8.InputStream stream=urlcon.getInputStream();  
9.int i;  
10.while((i=stream.read())!=-1){  
11.System.out.print((char)i);  
12.}  
13.}catch(Exception e){System.out.println(e);}  
16 14.}  
15.}  

RAISONI GROUP OF INSTITUTIONS


What is a Jar file?
JavaArchive(JAR) bundles all the classes in one package.
Since the archive is compressed and can be downloaded in a single HTTP connection,
it is often faster to download the archive than to download individual classes.
Although jar bundles all the classes, their fully classified names can be used to refer to
individual classes in case of need. Java provides several mechanisms to extract information from a jar file.
This article presents one of the ways using JarURLConnection class.
This class represents a URL connection to a jar file, entry or directory.
It can be used in scenarios when the programmer knows that the URL refers to a jar entry
and needs jar specific functionality.
Syntax of a Jar URL :-
Jar URL starts with the general URL that points to the location of jar archive.
Than “jar:” protocol is prefixed and finally “!/” and path to the file inside the
jar archive is suffixed in the end of this URL. For example,
jar:http://www.abcd.com/networking.jar!/com/foo/example.class
Java InetAddress class

Java InetAddress class represents an IP address.


The java.net.InetAddress class provides methods to get the IP of any host name
 for example  www.google.com, www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number.
An instance of InetAddress represents the IP address with its corresponding host name.

18

RAISONI GROUP OF INSTITUTIONS


Commonly used methods of InetAddress class

Method Description

public static InetAddress it returns the instance of InetAddress


getByName(String host) throws containing LocalHost IP and name.
UnknownHostException

public static InetAddress it returns the instance of


getLocalHost() throws InetAdddress containing local host
UnknownHostException name and address.

public String getHostName() it returns the host name of the IP


address.

public String getHostAddress() it returns the IP address in string


format.
Example of Java InetAddress class

import java.io.*;  
import java.net.*;  
public class InetDemo{  
public static void main(String[] args){  
try{  
InetAddress ip=InetAddress.getByName("www.google.com");  
  
System.out.println("Host Name: "+ip.getHostName());  
System.out.println("IP Address: "+ip.getHostAddress());  
}catch(Exception e){System.out.println(e);}  
}  
}  
Example of Java InetAddress class to find hostname from IP Address

import java.net.*;
public class NewClass1 {
public static void main(String[] args) {
InetAddress ip;
String hostname;
try {
ip = InetAddress.getLocalHost();
hostname = ip.getHostName();
System.out.println("Your current IP address : " + ip);
System.out.println("Your current Hostname : " + hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
Find the Output for following code
What will be the output of the following Java program?
1.import java.net.*;
2.class networking
3.{
4.public static void main(String[] args) throws UnknownHostException
5.{
6.InetAddress obj1 = InetAddress.getByName("cisco.com");
7.System.out.print(obj1.getHostName());
8.}
9.}
a) cisco
b) cisco.com
c) www.cisco.com
d) none of the mentioned
Find the Output for following code
1.import java.net.*;
2.public class networking
3.{
4.public static void main(String[] args) throws UnknownHostException
5.{
6.InetAddress obj1 = InetAddress.getByName("cisco.com");
7.InetAddress obj2 = InetAddress.getByName("sanfoundry.com");
8.boolean x = obj1.equals(obj2);
9.System.out.print(x);
10.}
11.}

a) 0
b) 1
c) true
d) false
Find the Output for following code
1.import java.net.*;
2.class networking
3.{
4.public static void main(String[] args) throws UnknownHostException
5.{
6.InetAddress obj1 = InetAddress.getByName("sanfoundry.com");
7.InetAddress obj2 = InetAddress.getByName("sanfoundry.com");
8.boolean x = obj1.equals(obj2);
9.System.out.print(x);
10.}
11.}

a) 0
b) 1
c) true
d) false
Answer Following questions

Which of these class is used to encapsulate IP address and DNS?


a)DatagramPacket
b) URL
c) InetAddress
d) ContentHandler

Which of these package contains classes and interfaces for networking?


a) java.io
b) java.util
c) java.net
d) java.network
Socket Programming
Socket class
A socket is simply an endpoint for communications between the machines.
The Socket class can be used to create a socket.

Important methods

Method Description

1) public InputStream returns the InputStream attached


getInputStream() with this socket.

2) public OutputStream returns the OutputStream attached


getOutputStream() with this socket.

3) public synchronized void close() closes this socket


Socket Programming
ServerSocket class
The ServerSocket class can be used to create a server socket.
This object is used to establish communication with the clients.

Important methods

Method Description

1) public Socket accept() returns the socket and establish a


connection between server and client.

2) public synchronized void close() closes the server socket.


Example of Java Socket Programming

Creating Server:
To create the server application, we need to create the instance of ServerSocket class.
Here, we are using 6666 port number for the communication between the client and
server. You may also choose any other port number. The accept() method waits for the
client. If clients connects with the given port number, it returns an instance of Socket.

1.ServerSocket ss=new ServerSocket(6666);  
2.Socket s=ss.accept();//establishes connection and waits for the client   

Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we
need to pass the IP address or hostname of the Server and a port number. Here, we are
using "localhost" because our server is running on same system.

3.Socket s=new Socket("localhost",6666);  
MyServer.java

1.import java.io.*;  
2.import java.net.*;  
3.public class MyServer {  
4.public static void main(String[] args){  
5.try{  
6.ServerSocket ss=new ServerSocket(6666);  
7.Socket s=ss.accept();//establishes connection   
8.DataInputStream dis=new DataInputStream(s.getInputStream());  
9.String  str=(String)dis.readUTF();  
10.System.out.println("message= "+str);  
11.ss.close();  
12.}catch(Exception e){System.out.println(e);}  
13.}  
14.}  
MyClient.java

1.import java.io.*;  
2.import java.net.*;  
3.public class MyClient {  
4.public static void main(String[] args) {  
5.try{      
6.Socket s=new Socket("localhost",6666);  
7.DataOutputStream dout=new DataOutputStream(s.getOutputStream
());  
8.dout.writeUTF("Hello Server");  
9.dout.flush();  
10.dout.close();  
11.s.close();  
12.}catch(Exception e){System.out.println(e);}  
13.}  
14.}  
DatagramSocket and DatagramPacket

Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

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.

Commonly used 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.
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
DatagramPacket(byte[] barr, int length): it creates a datagram packet.
This constructor is used to receive the packets.
DatagramPacket(byte[] barr, int length, InetAddress address, int
port): it creates a datagram packet. This constructor is used to send the
packets.
Example of Sending DatagramPacket by DatagramSocket

//DSender.java  
import java.net.*;  
public class DSender{  
  public static void main(String[] args) throws Exception {  
    DatagramSocket ds = new DatagramSocket();  
    String str = "Welcome java";  
    InetAddress ip = InetAddress.getByName("127.0.0.1");  
     
    DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(),
 ip, 3000);  
    ds.send(dp);  
    ds.close();  
  }  
}  
Example of Receiving DatagramPacket by DatagramSocket

//DReceiver.java  
import java.net.*;  
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 str = new String(dp.getData(), 0, dp.getLength());  
    System.out.println(str);  
    ds.close();  
  }  
}  

You might also like