AJ - Unit 1
AJ - Unit 1
AJ - Unit 1
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 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
• 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.
ServerSocket: Represents a server-side socket that listens for incoming client connections.
URL: Represents a Uniform Resource Locator for accessing resources on the internet.
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:
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:
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:
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:
Key Methods:
Usage:
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");
}
}
Priyakant Makwana
Advance Java
Purpose: RMI facilitates communication between distributed Java applications, enabling remote
method calls between objects in different JVMs.
Usage:
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.
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
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.
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 :
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.
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 “
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Calculator extends Remote
{
int add(int a, int b) throws RemoteException;
}
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
3. Server Implementation:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
System.out.println("Server is running...");
}
}
Priyakant Makwana
Advance Java
4. Client Implementation:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
int a = 10;
int b = 20;
int result = calculator.add(a, b);
Priyakant Makwana