AJ - Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Advance Java

Unit 1
Java Networking
 What is “Networking”?
- Getting two or more computers to send data (in Java-- serialized objects) to each other .
- Having programs on separate computers interact with one Another.

 Types of Networking.

Client - Server
Many clients connect with one server.
Clients communicate only with server.
Peer-to-Peer
Clients connect to a group of other clients, with no server.
Clients communicating directly with each-other.

 The term “ Network Programming “ refers to writing programs that execute across multiple
devices computers, in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the
low-level communication details, allowing you to write programs that focus on solving the
problem at hand.

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.
 UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.

 Socket Programming:

Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket to
a server.

When the connection is made, the server creates a socket object on its end of the communication.
The client and server can now communicate by writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.

The following steps occur when establishing a TCP connection between two computers using
sockets:

 The server instantiates a ServerSocket object, denoting which port number communication is
to occur on.

 The server invokes the accept method of the ServerSocket class. This method waits until a
client connects to the server on the given port.

 After the server is waiting, a client instantiates a Socket object, specifying the server name
and port number to connect to.

 The constructor of the Socket class attempts to connect the client to the specified server and
port number. If communication is established, the client now has a Socket object capable of
communicating with the server.

Priyakant Makwana
Advance Java

 On the server side, the accept method returns a reference to a new socket on the server that
is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket
has both an OutputStream and an InputStream. The client's OutputStream is connected to the
server's InputStream, and the client's InputStream is connected to the server's OutputStream.

TCP is a twoway communication protocol, so data can be sent across both streams at the same
time. There are following usefull classes providing complete set of methods to implement sockets.

 TCP/IP Client Server Sockets:


 TCP (Transmission Control Protocol) is great for applications that need reliable communication.
It's used by many protocols like HTTP, HTTPS, FTP, SMTP, and Telnet.

 TCP ensures data arrives intact and in order. It handles flow control, ensuring smooth
transmission, and uses a three-packet handshake to start connections.

 TCP also manages reliability and congestion, and if there are errors, it retransmits packets until
they're received correctly.

 TCP Server –
1. using create(), Create TCP socket.
2. using bind(), Bind the socket to server address.
3. using listen(), put the server socket in a passive mode, where it waits for the client to approach the
server to make a connection
4. using accept(), At this point, connection is established between client and server, and they are
ready to transfer data.
5. Go back to Step 3.

 TCP Client –
1. Create TCP socket.
2. connect newly created client socket to server.

Priyakant Makwana
Advance Java

 Client - Server Networking :

• Advantages:
-Easier to implement.
- Less coordination involved.
-Easier to maintain control of users.
• Disadvantage:
-Relies on one main server for entire operation.

 Java.net Package :
The java.net package in Java provides classes and interfaces for networking functionality.

Purpose: The java.net package offers classes and interfaces to facilitate network communication in
Java applications.

Key Classes and Interfaces:

 Socket: Represents a client-side socket for communication with a server.

 ServerSocket: Represents a server-side socket that listens for incoming client connections.

 InetAddress: Represents an IP address.

 URL: Represents a Uniform Resource Locator for accessing resources on the internet.

 URLConnection: Abstract class representing a connection to a URL.

 URLConnection: Subclasses of URLConnection handle specific protocols such as HTTP,


HTTPS, FTP, etc.

 DatagramSocket: Provides support for UDP (User Datagram Protocol) communication.

 DatagramPacket: Represents a packet of data to be sent or received via UDP.

Priyakant Makwana
Advance Java

 ServerSocket Class :
The ServerSocket class in Java networking is used for implementing server-side functionality, enabling
servers to accept incoming connections from clients.

Purpose: The ServerSocket class is used to create a server-side socket that listens for incoming
connections from clients in Java networking applications.

Functionality: It allows the server to passively wait for and accept incoming connections initiated by
clients.

Key Methods:

 ServerSocket(int port): Constructor for creating a ServerSocket instance bound to a specified


port.
 void bind(SocketAddress endpoint): Binds the server socket to a specific network address.
 Socket accept(): Listens for and accepts incoming connection requests from clients.
It blocks until a connection is established.
 void close(): Closes the server socket, stopping it from accepting further connections.

Usage:

 Typically used in server applications where the server needs to handle multiple client connections
simultaneously.
 After creating a ServerSocket, it continuously calls the accept() method in a loop to accept
incoming connections.
 Each accepted connection is represented by a Socket object, which can be used for
communication with the corresponding client.

 Socket Class :
The Socket class in Java networking facilitates communication between client and server applications
over TCP/IP.

Purpose: The Socket class represents an endpoint for communication between two machines over the
network.

Functionality:

 Enables client applications to establish connections to server applications.


 Provides input and output streams for sending and receiving data.
 Handles underlying network communication details, such as establishing connections and
managing data transmission.

Key Methods:

 Socket(String host, int port): Constructor for creating a socket and connecting it to the specified
host and port.
 InputStream getInputStream(): Retrieves the input stream associated with the socket for
receiving data.
 OutputStream getOutputStream(): Retrieves the output stream associated with the socket for
sending data.
 void close(): Closes the socket and releases its resources.

Usage:

 Used in client-server applications to establish connections and exchange data.


Provides a simple and efficient way to implement network communication in Java programs.

Priyakant Makwana
Advance Java

 URL Class :
The URL class in Java networking is used to represent and manipulate Uniform Resource Locators
(URLs). Here's a concise summary:

Purpose: The URL class is used to parse, construct, and represent URLs, which are addresses used to
locate resources on the internet or within a network.

Functionality:

 Parses URLs into their components such as protocol, host, port, path, query parameters, and
fragment.
 Constructs URLs from their individual components.
 Provides methods for accessing and manipulating different parts of the URL.

Key Methods:

 URL(String spec): Constructor for creating a URL object from a string representation of the
URL.
 openConnection(): Opens a connection to the URL and returns a URLConnection object for
further communication.
 String getProtocol(), String getHost(), int getPort(), String getPath(), etc.: Methods to retrieve
specific components of the URL.
 String toString(): Returns the string representation of the URL.

Usage:

 Used in web development, networking, and various applications requiring URL handling.
Allows developers to work with URLs, access resources over the internet, and establish connections to
remote servers.

Example :

import java.net.*;
public class URL_Example
{
public static void main(String args[])
{
Try
{
URL url=new URL("https://cutshort.io/blog/category/career-advice");

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)
{
E.printStackTrace();
}
}
}

Priyakant Makwana
Advance Java

 URLConnection Class :
The URLConnection class in Java networking facilitates communication with a remote resource
identified by a URL.

Purpose: URLConnection represents a communication link between the application and a URL for
reading from or writing to the resource referenced by the URL.

Functionality:

 Provides an abstract base class for specific protocol implementations (e.g., HTTP, HTTPS, FTP)
to handle communication with remote servers.
 Supports various types of connections, including input and output streams, for reading from and
writing to the resource.
Key Methods:

 InputStream getInputStream(): Returns an input stream that reads from the resource referenced by
the URL.
 OutputStream getOutputStream(): Returns an output stream that writes to the resource referenced
by the URL.
 void connect(): Establishes the connection to the remote resource.
 void setRequestProperty(String key, String value): Sets a general request property for the
connection.
Usage:

 Utilized in applications requiring interaction with remote resources identified by URLs, such as
web scraping, file downloading, or accessing web APIs.
 Allows developers to retrieve data from web servers or upload data to remote servers
programmatically.

Example :

import java.io.*;
import java.net.*;
public class URLConnection_Example
{
public static void main(String args[])
{

Try
{
URL U1=new URL("https://cutshort.io/blog/category/hiring");

URLConnection U2=U1l.openConnection();

InputStream IS=U2.getInputStream();

int i;
while((i=IS.read())!=-1)
{
System.out.print((char)i);
}
}
catch(Exception e)
{
e.printStackTrace();
}

Priyakant Makwana
Advance Java

}
 InetAddress Class :
The InetAddress class in Java networking is used to represent IP addresses and perform domain name
resolution. :

Purpose: The InetAddress class is used to represent both IPv4 and IPv6 addresses and to perform
hostname-to-IP address resolution and vice versa.

Functionality:

 Provides methods for creating instances representing IP addresses and hostnames.


 Supports methods for querying hostname information from an IP address and vice versa.
 Offers utility methods for checking reachability and getting the hostname and IP address of the
local machine.

Key Methods:

 getByName(String host): Returns an InetAddress instance representing the specified hostname


or IP address.
 getHostAddress(): Returns the IP address string in textual presentation.
 getHostName(): Returns the fully qualified domain name for this IP address.

Usage:

 Used in networking applications to resolve hostnames to IP addresses and vice versa.


 Facilitates communication between networked devices by converting between hostnames and IP
addresses.

Example :

import java.io.*;
import java.net.*;
public class InetAddress_Example
{
public static void main(String args[])
{
Try
{
InetAddress ip=InetAddress.getByName("https://cutshort.io/resources/case-studies");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e)
{
e.printStackTrace();
}

}
}

Priyakant Makwana
Advance Java

 Remote Method Invocation :


RMI (Remote Method Invocation) architecture in Java networking allows objects residing on one Java
Virtual Machine (JVM) to invoke methods on objects residing on another JVM.

Purpose: RMI facilitates communication between distributed Java applications, enabling remote
method calls between objects in different JVMs.

Usage:

 Used in distributed applications where components need to communicate across network


boundaries.
 Facilitates building client-server applications, distributed systems, and remote services in Java.

In an RMI application, we write two programs, a server program (resides on the server) and a client
program (resides on the client).

Inside the server program, a remote object is created and reference of that object is made available for
the client (using the Registry).

The client program requests the remote objects on the server and tries to invoke its methods.

 The following diagram shows the architecture of an RMI application.

 Let us now discuss the components of this architecture.

 Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.

 Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client
system; it acts as a gateway for the client program.

 Skeleton − This is the object which resides on the server side. stub communicates with this
skeleton to pass request to the remote object.

 RRL(Remote Reference Layer) − It is the layer which manages the references made by the
client to the remote object.

Priyakant Makwana
Advance Java

 Working of an RMI Application :

The following points summarize how an RMI application works −

 When the client makes a call to the remote object, it is received by the stub which eventually
passes this request to the RRL.

 When the client-side RRL receives the request, it invokes a method called invoke() of the object
remoteRef. It passes the request to the RRL on the server side.

 The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally
invokes the required object on the server.

 The result is passed all the way back to the client.

 RMI Registry :
RMI registry is a namespace on which all server objects are placed. Each time the server creates an
object, it registers this object with the RMIregistry (using bind() or reBind() methods). These are
registered using a unique name known as bind name.

To invoke a remote object, the client needs a reference of that object. At that time, the client fetches the
object from the registry using its bind name (using lookup() method).

Priyakant Makwana
Advance Java

 Additional Topics :

“ Difference between TCP & UDP “

TCP UDP
Full form It stands for Transmission It stands for User Datagram
Control Protocol. Protocol.
Type of Connection It is a connection-oriented It is a connectionless protocol,
protocol, which means that the which means that it sends the
connection needs to be data without checking whether
established before the data is the system is ready to receive or
transmitted over the network. not.

Reliable TCP is a reliable protocol as it UDP is an unreliable protocol as


provides assurance for the it does not take the guarantee for
delivery of data packets. the delivery of packets.
Speed TCP is slower than UDP as it UDP is faster than TCP as it
performs error checking, flow does not guarantee the delivery
control, and provides assurance of data packets.
for the delivery of
Header Size The size of TCP is 20 bytes. The size of the UDP is 8 bytes.
Acknowledgment TCP uses the three-way- UDP does not wait for any
handshake concept. In this acknowledgment; it just sends
concept, if the sender receives the data.
the ACK, then the sender will
send the data. TCP also has the
ability to resend the lost data.
Flow control mechanism It follows the flow control This protocol follows no such
mechanism in which too many mechanism.
packets cannot be sent to the
receiver at the same time.
Error checking TCP performs error checking by It does not perform any error
using a checksum. When the checking, and also does not
data is corrected, then the data is resend the lost data packets.
retransmitted to the receiver.
Applications This protocol is mainly used This protocol is used where fast
where a secure and reliable communication is required and
communication process is does not care about the
required, like military services, reliability like VoIP, game
web browsing, and e-mail. streaming, video and music
streaming, etc.

Priyakant Makwana
Advance Java

“ Write an RMI application where clientsupplies two numbers and server response
bysumming it. Provide your custom security policy for this application “

1. Define Remote Interface:

import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Calculator extends Remote
{
int add(int a, int b) throws RemoteException;
}

2. Implement Remote Interface:

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class CalculatorImpl extends UnicastRemoteObject implements Calculator


{
protected CalculatorImpl() throws RemoteException
{
super();
}

public int add(int a, int b) throws RemoteException {


return a + b;
}
}

3. Server Implementation:

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Server


{
public static void main(String[] args) throws Exception
{
System.setProperty("java.security.policy", "server.policy");
System.setSecurityManager(new SecurityManager());

Registry registry = LocateRegistry.createRegistry(1099);


registry.rebind("CalculatorService", new CalculatorImpl());

System.out.println("Server is running...");
}
}

Priyakant Makwana
Advance Java

4. Client Implementation:

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {


public static void main(String[] args) throws Exception {
System.setProperty("java.security.policy", "client.policy");
System.setSecurityManager(new SecurityManager());

Registry registry = LocateRegistry.getRegistry("localhost", 1099);


Calculator calculator = (Calculator) registry.lookup("CalculatorService");

int a = 10;
int b = 20;
int result = calculator.add(a, b);

System.out.println("Sum of " + a + " and " + b + " is: " + result);


}
}

Priyakant Makwana

You might also like