0% found this document useful (0 votes)
49 views59 pages

Java Unit 2 NOTES

The document covers advanced networking concepts in Java, including socket programming, TCP/IP, and UDP protocols. It explains the use of Java classes such as Socket, ServerSocket, and URLConnection for establishing client-server communication and data exchange. Additionally, it provides examples of server and client applications demonstrating socket communication and URL handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views59 pages

Java Unit 2 NOTES

The document covers advanced networking concepts in Java, including socket programming, TCP/IP, and UDP protocols. It explains the use of Java classes such as Socket, ServerSocket, and URLConnection for establishing client-server communication and data exchange. Additionally, it provides examples of server and client applications demonstrating socket communication and URL handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS2210501- ADVANCED JAVA PROGRAMMING

UNIT-II - ADVANCE NETWORKING

Networking Basics - Introduction of Socket - Types of Socket - Socket API - TCP-IP:

Client/Server Sockets – URL - UDP: Datagrams - [Link] package classes: Socket– ServerSocket -

InetAddress – URL – URL Connection - RMI Architecture - Client Server Application using

RMI.

NETWORKING BASICS

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.

1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Advantage of Java Networking

1. sharing resources
2. centralize software management

Java Networking Terminology


The widely used java networking terminologies,

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

IP Address
IP address is a unique number assigned to a node of a network e.g. [Link]. It is
composed of octets that range from 0 to 255. It is a logical address that can be changed.
Protocol

A protocol is a set of rules basically that is followed for communication. For


example:

2
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● TCP
● FTP
● Telnet
● SMTP
● POP

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.

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

3
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

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.

Socket

A socket is an endpoint between two way communications.

JAVA SOCKET PROGRAMMING

Java Socket programming is used for communication between the applications


running on different JRE. Java Socket programming can be connection-oriented or
connection-less. Socket and ServerSocket classes are used for connection-oriented
socket programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming. The client in socket programming must know
two information:

1. IP Address of Server, and


2. Port number.

4
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

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

returns the InputStream attached with this


1) public InputStream getInputStream()
socket.

returns the OutputStream attached with this


2) public OutputStream getOutputStream()
socket.

3) public synchronized void close() closes this socket

5
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

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

returns the socket and establish a


1) public Socket accept()
connection between server and client.

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

6
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Example of Java Socket


Programming [Link]

import
[Link].
*;
import
[Link]
t.*;

public class MyServer {

public static void


main(String[] args){ try{

ServerSocket ss=new
ServerSocket(6666); Socket

7
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

s=[Link]();//establishes
connection

DataInputStream dis=new
DataInputStream([Link]()); String
str=(String)[Link]();

[Link]("message= "+str);
[Link]();
}catch(Exception e){[Link](e);}
}}
[Link]
import [Link].*; import [Link].*;
public class MyClient {

public static void


main(String[] args) { try{

8
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Socket s=new Socket("localhost",6666);

DataOutputStream dout=new
DataOutputStream([Link]()); [Link]("Hello
Server");

[Link]();
[Link]();
[Link]();
}catch(Exception e){[Link](e);}
}
}

To execute this program open two command prompts and execute each
program at each command prompt as displayed in the below figure. After running the
client application, a message will be displayed on the server console.

9
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

TYPES OF SOCKET
1. TCP Sockets (Connection-Oriented):
[Link]:
Represents a client-side socket used to establish a connection to a server.
[Link]:
Represents a server-side socket that listens for incoming client connections on a specific port.
Characteristics:

● Reliable, ordered, and error-checked data transmission.


● Requires a connection setup before data transfer.

10
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● Provides a bidirectional stream of data.


● Suitable for applications requiring guaranteed delivery, such as web browsing and file
transfer.

2. UDP Sockets (Connectionless):


[Link]: Used for sending and receiving datagram packets.
Characteristics:

● Unreliable, unordered, and no delivery guarantees.


● No connection setup is required.
● Data is sent in packets, and each packet is treated independently.
● Suitable for applications like streaming media and online gaming, where speed is
prioritized over reliability.

3. Multicast Sockets:
[Link]:
A subclass of DatagramSocket used for sending and receiving data to multiple recipients
simultaneously.
Characteristics:

11
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● Allows data to be sent to a group of hosts.


● Useful for applications like video conferencing and online gaming.

4. Raw Sockets
Characteristics:

● Provide access to the underlying transport provider.


● Typically datagram-oriented
● Used for development of new communication protocols or for access to more esoteric
facilities of an existing protocol.

Socket Type Protocol Communication Reliability Java Classes


Connection- Reliable,
Stream Socket TCP Socket, ServerSocket
oriented ordered
Datagram DatagramSocket,
UDP Connectionless Unreliable
Socket DatagramPacket

SOCKET API
The Socket API in Java provides a way for programs to communicate with each other over a
network. It allows for the creation of connections between applications, enabling the exchange of
data.

12
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Core Functionality
Sockets as Endpoints:

● A socket represents one end of a two-way communication link between two programs.

Client-Server Model:

● Typically, one program acts as a server, listening for incoming connections, while
another program acts as a client, initiating connections to the server.

IP Addresses and Ports:

● Communication requires knowing the IP address of the machine and the specific port
number on which the application is listening.

Data Streams:

● Once a connection is established, data is exchanged through input and output streams.
Key Classes

● [Link]: This class represents a client socket, used to establish a connection to a server.
● [Link]: This class represents a server socket, used to listen for incoming client
connections.
Communication Protocols

13
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

TCP (Transmission Control Protocol):

● A connection-oriented protocol, ensuring reliable and ordered delivery of data.

UDP (User Datagram Protocol):

● A connectionless protocol, offering faster but potentially unreliable data transfer.

Common Operations
Creating Sockets:

● Socket objects are created to connect to a server.


● ServerSocket objects are created to listen for incoming connections.

Establishing Connections:

● Clients connect to servers using the server's IP address and port number.
● Servers accept incoming connections from clients.

Sending and Receiving Data:

14
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● Data is sent through output streams.


● Data is received through input streams.

Closing Connections:

● Sockets are closed to terminate communication.

import [Link].*;

import [Link].*;

public class SimpleClient {

public static void main(String[] args) throws IOException {

Socket socket = new Socket("[Link]", 12345); // Connect to localhost on port 12345

PrintWriter out = new PrintWriter([Link](), true);

BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));

[Link]("Hello from client!");

String response = [Link]();

[Link]("Server says: " + response);

[Link]();

public class SimpleServer {

15
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

public static void main(String[] args) throws IOException {

ServerSocket serverSocket = new ServerSocket(12345); // Listen on port 12345

Socket clientSocket = [Link](); // Accept incoming connection

PrintWriter out = new PrintWriter([Link](), true);

BufferedReaderin=newBufferedReader(newInputStreamReader([Link]()));

String message = [Link]();

[Link]("Client says: " + message);

[Link]("Hello from server!");

[Link]();

[Link]();

TCP-IP: CLIENT/SERVER SOCKETS


TCP/IP (Transmission Control Protocol/Internet Protocol) is a suite of communication protocols
used to interconnect network devices on the internet. TCP is a connection-oriented protocol,
whereas UDP (User Datagram Protocol) is a simpler, connectionless internet protocol.

Server-Side Programming
1. Establish a Socket Connection
To create a server application two sockets are needed.

● ServerSocket: This socket waits for incoming client requests. It listens for connections on a
specific port.

16
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● Socket: Once a connection is established, the server uses this socket to communicate with the
client.
2. Communication
● Once the connection is established, you can send and receive data through the socket using
streams.
● The getOutputStream() method is used to send data to the client.
3. Close the Connection
Once communication is finished, it's important to close the socket and the input/output streams to
free up resources.

TCP Server:

import [Link].*;

import [Link].*;

public class Server {

public static void main(String[] args) throws IOException {

ServerSocket serverSocket = new ServerSocket(6666);

[Link]("Server started");

Socket socket = [Link](); // Establishes connection

[Link]("Client connected");

// Receiving data from client

DataInputStream in = new DataInputStream([Link]());

[Link]("Client says: " + [Link]());

[Link]();

17
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Client-Side Programming
1. Establish a Socket Connection
To connect to another machine we need a socket connection. A socket connection means both
machines know each other’s IP address and TCP port. The [Link] class is used to
create a socket.
Socket socket = new Socket(“[Link]”, 5000)

● The first argument: The IP address of Server i.e. [Link] is the IP address of localhost,
where code will run on the single stand-alone machine.
● The second argument: The TCP Port number (Just a number representing which
application to run on a server. For example, HTTP runs on port 80. Port number can be from
0 to 65535)
2. Communication
To exchange data over a socket connection, streams are used for input and output:

● Input Stream: Reads data coming from the socket.


● Output Stream: Sends data through the socket.

Example to access these streams:

18
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

// to read data
InputStream input = [Link]();
// to send data
OutputStream output = [Link]();
3. Closing the Connection
The socket connection is closed explicitly once the message to the server is sent.

TCP Client:

import [Link].*;

import [Link].*;

public class Client {

public static void main(String[] args) throws IOException {

Socket socket = new Socket("localhost", 6666);

[Link]("Connected to server");

// Sending data to server

DataOutputStream out = new DataOutputStream([Link]());

[Link]("Hello Server");

[Link]();

Run the Application

19
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Open two windows one for Server and another for Client.
1. Run the Server
First run the Server application as:
$ java Server

Output:
Server started
Waiting for a client ...

2. Run the Client


Then run the Client application on another terminal as
$ java Client

Output:
Connected

3. Exchange Messages
● Type messages in the Client window.
● Messages will appear in the Server window.
● Type "Over" to close the connection.
Here is a sample interaction,
Client:
Hello
I made my first socket connection
Over

Server:
Hello
I made my first socket connection

20
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Over
Closing connection

JAVA URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example: [Link] A URL
contains many information

1. Protocol: In this case, http is the protocol.

2. Server name or IP Address: In this case, [Link] is the server name.

3. Port Number: It is an optional attribute. If we write


http//[Link]/sonoojaiswal/ , 80 is the port number. If port number is not
mentioned in the URL, it returns -1.

4. File Name or directory name: In this case, [Link] is the file name.

Methods of Java URL class

The [Link] class provides many methods. The important methods of URL class.

Method Description

Public String getProtocol() It returns the protocol of the URL.

21
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Method Description

Public String getHost() It returns the host name of the URL.

Public String getPort() It returns the Port Number of the URL.

Public String getFile() It returns the file name of the URL.

Public URLConnection openConnection() It returns the instance of URL Connection


i.e. associated with this URL.

Example of Java URL class

//[Link]

import [Link].*;

import [Link].*;

22
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

public class URLDemo{

public static void main(String[] args){

try{

URL url=new URL("[Link]

[Link]("Protocol: "+[Link]());

[Link]("Host Name: "+[Link]());

[Link]("Port Number: "+[Link]());

[Link]("File Name: "+[Link]());

catch(Exception e)

[Link](e);

Output:

Protocol: http

Host Name: [Link]

Port Number: -1

File Name: /java-tutorial

Java URLConnection class

23
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

The Java URLConnection class 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.

Get the object of URLConnection class

The openConnection() method of URL class returns the object of URLConnection class.

Syntax:

public URLConnection openConnection()throws IOException{}

Displaying source code of a webpage by URLConnecton class

The URLConnection class provides many methods, we can display all the data of a

webpage by using the getInputStream() method. The getInputStream() method returns all the

data of the specified URL in the stream that can be read and displayed.

Example of Java URLConnection class

import [Link].*;

import [Link].*;

public class URLConnectionExample {

public static void main(String[] args){

try{

URL url=new URL("[Link]

URLConnection urlcon=[Link]();

InputStream stream=[Link]();

int i;

24
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

while((i=[Link]())!=-1)

[Link]((char)i);

}catch(Exception e){[Link](e);}

Java HttpURLConnection class

The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol
only. By the help of HttpURLConnection class, you can information of any HTTP URL such as
header information, status code, response code etc. The [Link] is subclass
of URLConnection class.

Get the object of HttpURLConnection class

The openConnection() method of URL class returns the object of URLConnection class.

Syntax:

public URLConnection openConnection()throws IOException{}

URL url=new URL("[Link]

HttpURLConnection huc=(HttpURLConnection)[Link]();

Java HttpURLConnecton Example

import [Link].*;

import [Link].*;

public class HttpURLConnectionDemo{

25
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

public static void main(String[] args){

try{

URL url=new URL("[Link]

HttpURLConnection huc=(HttpURLConnection)[Link]();

for(int i=1;i<=8;i++){

[Link]([Link](i)+" = "+[Link](i));

[Link]();

}catch(Exception e){[Link](e);}

Output:

Date = Wed, 10 Dec 2014 [Link] GMT

Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/

Content-Type = text/html

Cache-Control = max-age=2592000

Expires = Fri, 09 Jan 2015 [Link] GMT

Vary = Accept-Encoding,User-Agent

Connection = close

Transfer-Encoding = chunked

UDP: DATAGRAMS

26
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

User Datagram Protocol (UDP) is a Transport Layer protocol. UDP is a part of the Internet
Protocol suite, referred to as UDP/IP suite. Unlike TCP, it is an unreliable and connectionless
protocol. So, there is no need to establish a connection before data transfer. The UDP helps to
establish low-latency and loss-tolerating connections over the network. The UDP enables
process-to-process communication.

What is User Datagram Protocol?


User Datagram Protocol (UDP) is one of the core protocols of the Internet Protocol (IP) suite. It
is a communication protocol used across the internet for time-sensitive transmissions such as
video playback or DNS lookups . Unlike Transmission Control Protocol (TCP), UDP is
connectionless and does not guarantee delivery, order, or error checking, making it a lightweight
and efficient option for certain types of data transmission.

UDP Header
UDP header is an 8-byte fixed and simple header, while for TCP it may vary from 20 bytes to 60
bytes. The first 8 Bytes contain all necessary header information and the remaining part consists
of data. UDP port number fields are each 16 bits long, therefore the range for port numbers is
defined from 0 to 65535; port number 0 is reserved. Port numbers help to distinguish different
user requests or processes.

27
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● Source Port: Source Port is a 2 Byte long field used to identify the port number of the source.
● Destination Port: It is a 2 Byte long field, used to identify the port of the destined packet.
● Length: Length is the length of UDP including the header and the data. It is a 16-bits field.
● Checksum: Checksum is 2 Bytes long field. It is the 16-bit one's complement of the one's
complement sum of the UDP header, the pseudo-header of information from the IP header,
and the data, padded with zero octets at the end (if necessary) to make a multiple of two
octets.
Applications of UDP
● Used for simple request-response communication when the size of data is less and hence there
is lesser concern about flow and error control.
● It is a suitable protocol for multicasting as UDP supports packet switching.
● UDP is used for some routing update protocols like RIP(Routing Information Protocol).
● Normally used for real-time applications which can not tolerate uneven delays between
sections of a received message.
● VoIP (Voice over Internet Protocol) services, such as Skype and WhatsApp, use UDP for
real-time voice communication. The delay in voice communication can be noticeable if
packets are delayed due to congestion control, so UDP is used to ensure fast and efficient data
transmission.

28
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● DNS (Domain Name System) also uses UDP for its query/response messages. DNS queries
are typically small and require a quick response time, making UDP a suitable protocol for this
application.
● DHCP (Dynamic Host Configuration Protocol) uses UDP to dynamically assign IP addresses
to devices on a network. DHCP messages are typically small, and the delay caused by packet
loss or retransmission is generally not critical for this application.
● Following implementations uses UDP as a transport layer protocol:

o NTP (Network Time Protocol)


o DNS (Domain Name Service)
o BOOTP, DHCP.
o NNP (Network News Protocol)
o Quote of the day protocol
o TFTP, RTSP, RIP.
● The application layer can do some of the tasks through UDP-

o Trace Route
o Record Route
o Timestamp
Advantages of UDP
● Speed: UDP is faster than TCP because it does not have the overhead of establishing a
connection and ensuring reliable data delivery.
● Lower latency: Since there is no connection establishment, there is lower latency and faster
response time.
● Simplicity: UDP has a simpler protocol design than TCP, making it easier to implement and
manage.
● Broadcast support: UDP supports broadcasting to multiple recipients, making it useful for
applications such as video streaming and online gaming.
● Smaller packet size: UDP uses smaller packet sizes than TCP, which can reduce network
congestion and improve overall network performance.
● User Datagram Protocol (UDP) is more efficient in terms of both latency and bandwidth.
Disadvantages of UDP
● No reliability: UDP does not guarantee delivery of packets or order of delivery, which can
lead to missing or duplicate data.

29
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● No congestion control: UDP does not have congestion control, which means that it can send
packets at a rate that can cause network congestion.
● Vulnerable to attacks: UDP is vulnerable to denial-of-service attacks , where an attacker can
flood a network with UDP packets, overwhelming the network and causing it to crash.
● Limited use cases: UDP is not suitable for applications that require reliable data delivery,
such as email or file transfers, and is better suited for applications that can tolerate some data
loss, such as video streaming or online gaming.

[Link] PACKAGE CLASSES


The [Link] package provides classes for network communication in Java. It supports both
low-level and high-level networking functionalities, including TCP/IP, UDP, sockets, URLs,
and more.

Overview of [Link] Package

● Enables network programming using Java.


● Supports:
o TCP/IP (e.g., Socket, ServerSocket)
o UDP (e.g., DatagramSocket, DatagramPacket)
o URLs and connections (e.g., URL, URLConnection)
o IP addressing (e.g., InetAddress)
o RMI support (indirectly supports remote method invocation)

Commonly Used Classes in [Link]

Class Name Description


InetAddress Represents an IP address (IPv4 or IPv6). Used to get IP of host.
Implements a client socket (TCP). Used for communication between client
Socket
and server.
ServerSocket Used to create a server socket that waits for client connections (TCP).
DatagramSocket Used for sending/receiving packets via UDP.
DatagramPacket Represents the actual data packet used in UDP communication.

30
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Class Name Description


Represents a Uniform Resource Locator. Used for connecting to internet
URL
resources.
URLConnection Represents a connection to the resource referred by a URL.
HttpURLConnection Subclass of URLConnection. Used specifically for HTTP protocol.
URLEncoder Encodes string for safe inclusion in URLs (e.g., spaces to %20).
URLDecoder Decodes a URL-encoded string back to normal format.
ContentHandler Determines how content from a URL should be handled.
SocketAddress Encapsulates an IP address and port number.

3. Class Descriptions with Usage Examples

InetAddress

● Represents an IP address.
● Key methods:

o getLocalHost()
o getByName(String host)
o getHostAddress()

syntax:

InetAddress address = [Link]("[Link]");

31
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

[Link]([Link]());

Socket (Client Side - TCP)

● Connects to a server socket.

Syntax:

Socket socket = new Socket("localhost", 1234);

ServerSocket (Server Side - TCP)

● Waits for client connections.

Syntax:

ServerSocket server = new ServerSocket(1234);

Socket client = [Link]();

32
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

DatagramSocket&DatagramPacket (UDP)

● Used for connectionless communication.

Syntax:

DatagramSocket socket = new DatagramSocket(); // Client

DatagramPacket packet = new DatagramPacket(data, [Link], address, port);

[Link](packet);

URL&URLConnection

● Used to access resources over the internet.

Syntax:

URL url = new URL("[Link]

URLConnection connection = [Link]();

InputStream in = [Link]();

33
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

HttpURLConnection

● Subclass of URLConnection for handling HTTP requests directly.

Syntax:

HttpURLConnection conn = (HttpURLConnection) [Link]();

[Link]("GET");

Common Use Cases

Task Class(es) Used


Access a webpage URL, URLConnection, InputStream
Create a chat server Socket, ServerSocket
Send data without connection DatagramSocket, DatagramPacket
Resolve domain to IP address InetAddress
Encode/Decode URL parameters URLEncoder, URLDecoder

Summary Table:

Class Name TCP/UDP/Other Purpose


InetAddress Other IP Address handling
Socket TCP Client-side socket
ServerSocket TCP Server-side socket
DatagramSocket UDP Sending and receiving UDP packets
DatagramPacket UDP Represents data packet for UDP

34
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Class Name TCP/UDP/Other Purpose


URL Other Represents a web resource
URLConnection Other Manages connection to a resource

SOCKET – SERVERSOCKET
ServerSocket Class in Java provides a system-independent way to implement the server side of
a client/server socket connection. The constructor for ServerSocket throws an exception if it
can’t listen on the specified port (for example, the port is already being used).
1. In the [Link] channel, ServerSocket class is used for retrieving a ServerSocket associated
with this channel.
2. In [Link], ServerSocket class is used to create a server socket on the specified port
(port 0 indicates an anonymous port).
3. In [Link], the ServerSocket is used widely to:
● return an unbound server socket.
● return a server socket bound to the specified port.
● return a server socket bound to the specified port, and uses the specified connection
backlog.
● return a server socket bound to the specified port, with a specified listen backlog and
local IP.
Server-Side Programming
The below Java program demonstrates the working of server-side programming using
ServerSocket class.
// Java program demonstrates the

// working of server-side programming

// using ServerSocket class

import [Link].*;

import [Link].*;

import [Link].*;

35
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

import [Link].*;

public class MyServer {

public static void main(String[] args) {

try {

[Link]("Starting server...");

// Create a ServerSocket listening on port 6666

ServerSocket ss = new ServerSocket(6666);

[Link]("Server started. Listening on port 6666...");

// Accept a connection from a client

Socket s = [Link]();

[Link]("Client connected!");

// Read the message from the client

DataInputStream d = new DataInputStream([Link]());

String str = [Link]();

[Link]("Message: " + str);

// Close the socket

36
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

[Link]();

} catch (Exception e) {

[Link]("Server Error: " + e);

Output:

Explanation: In the above example, it demonstrates a basic server-side implementation using


the ServerSocket class. It listens on port 6666, accepts a client connection, reads a message sent
by the client, and then closes the connection.

Client-Side Programming
The below Java program demonstrate the working of client-side programming using
ServerSocket class.
// Java program demonstrates the

// working of client-side programming

// using ServerSocket class

37
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

import [Link].*;

import [Link].*;

public class MyClient {

// Main driver method

public static void main(String[] args) {

// Try block to check if exception occurs

try {

// Creating Socket class object and

// initializing Socket

Socket s = new Socket("localhost", 6666);

DataOutputStream d = new DataOutputStream(

[Link]());

// Message to be displayed

[Link]("Hello GFG Readers!");

38
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

// Flushing out internal buffers,

// optimizing for better performance

[Link]();

// Closing the connections

// Closing DataOutputStream

[Link]();

// Closing socket

[Link]();

// Catch block to handle exceptions

catch (Exception e) {

// Print the exception on the console

[Link](e);

Output:

39
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Explanation: In the above example, it demonstrates a basic client-side implementation using


the Socket class. It connects to a server at localhost on port 6666, sends a message "Hello GFG
Readers!", and then closes the connection.

Methods of Java ServerSocket

Method Description

Listens for a connection to be made to this socket


accept()
and accepts it.

Binds the ServerSocket to a specific address (IP


bind(SocketAddress endpoint)
address and port number).

Binds the ServerSocket to a specific address (IP


address and port number) and requests queqe length.
bind(SocketAddress endpoint, int backlog)
If a request arrives when the queue is full then the
request will be rejected by the server.

close() Closes this socket

40
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Method Description

Returns the unique ServerSocketChannel object


getChannel()
associated with this socket, if any.

getInetAddress() Returns the local address of this server socket.

Returns the port number on which this socket is


getLocalPort()
listening.

Returns the address of the endpoint this socket is


getLocalSocketAddress()
bound to, or null if it is not bound yet.

Gets the value of the SO_RCVBUF option for this


ServerSocket, that is the proposed buffer size that
getReceiveBufferSize()
will be used for Sockets accepted from this
ServerSocket.

getReuseAddress() Tests if SO_REUSEADDR is enabled.

getSoTimeout() Retrieve setting for SO_TIMEOUT.

Subclasses of ServerSocket use this method to


implAccept(Socket s) override accept() to return their own subclass
of the socket.

41
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Method Description

isBound() Returns the binding state of the ServerSocket.

isClosed() Returns the closed state of the ServerSocket.

setPerformancePreferences(int
Sets performance preferences for this ServerSocket
connectionTime, int latency, int bandwidth)

Sets performance preferences for this Sets a default proposed value for the SO_RCVBUF
ServerSocket option for sockets accepted from this ServerSocket.

setReuseAddress(boolean on) Enable/disable the SO_REUSEADDR socket option.

Sets the server socket implementation factory for the


setSocketFactory(SocketImplFactory fac)
application.

Enable/disable SO_TIMEOUT with the specified


setSoTimeout(int timeout)
timeout, in milliseconds.

Returns the implementation address and


toString()
implementation port of this socket as a String.

INETADDRESS – URL

42
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

The InetAddress class in Java represents an Internet Protocol (IP) address. It is used to
encapsulate IP addresses and is used by other networking classes, such as Socket, ServerSocket,
and URL. Here's how you can use InetAddress with URLs:

1. Getting the IP Address from a URL


The [Link](String host) method takes a hostname (like a URL) as input and
returns an InetAddress object representing the IP address associated with that hostname.

import [Link];

import [Link];

public class InetAddressExample {

public static void main(String[] args) {

try {

// Get InetAddress for a URL

String urlString = "[Link]";

InetAddress address = [Link](urlString);

// Print the IP address

[Link]("IP Address of " + urlString + ": " + [Link]());

} catch (UnknownHostException e) {

[Link]("Could not find IP address for the given URL.");

[Link]();

43
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

2. Getting Hostname from an IP Address


You can also use [Link](String host) with an IP address string as input. Then,
you can use getHostName() to get the host name associated with that IP address.

import [Link];

import [Link];

public class InetAddressExample {

public static void main(String[] args) {

try {

// Get InetAddress for an IP address

String ipAddressString = "[Link]";

InetAddress address = [Link](ipAddressString);

// Print the hostname

[Link]("Hostname of " + ipAddressString + ": " + [Link]());

} catch (UnknownHostException e) {

[Link]("Could not find hostname for the given IP address.");

44
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

[Link]();

3. Getting All IP Addresses for a Hostname


A hostname can have multiple IP addresses associated with it. You can retrieve all of them
using [Link](String host).

import [Link];

import [Link];

public class InetAddressExample {

public static void main(String[] args) {

try {

// Get all InetAddresses for a URL

String urlString = "[Link]";

InetAddress[] addresses = [Link](urlString);

[Link]("All IP Addresses for " + urlString + ":");

for (InetAddress addr : addresses) {

[Link]([Link]());

45
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

} catch (UnknownHostException e) {

[Link]("Could not find IP addresses for the given URL.");

[Link]();

4. Getting Local Host Address


You can get the IP address of the local machine using [Link]().

import [Link];

import [Link];

public class InetAddressExample {

public static void main(String[] args) {

try {

// Get the local host's InetAddress

InetAddress localhost = [Link]();

// Print local host information

[Link]("Local Host Address: " + [Link]());

46
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

[Link]("Local Host Name: " + [Link]());

} catch (UnknownHostException e) {

[Link]("Could not find local host information.");

[Link]();

● The InetAddress class does not create a URL object. It is used to resolve IP addresses from
hostnames or vice-versa.
● UnknownHostException is thrown if a hostname cannot be resolved to an IP address or vice-
versa.
● InetAddress can represent both IPv4 and IPv6 addresses.
● getHostAddress() returns the IP address as a string.
● getHostName() returns the hostname associated with the IP address.

URL CONNECTION
URLConnection Class in Java is an abstract class that represents a connection of a resource as
specified by the corresponding URL. It is imported by the [Link] package.
The URLConnection class is utilized for serving two different yet related purposes, Firstly it
provides control on interaction with a server(especially an HTTP server) than URL class.
Secondly, with a URLConnection we can check the header sent by the server and respond

47
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

accordingly, we can configure header fields used in client requests. We can also download binary
files by using URLConnection.

URL is an acronym of Uniform resource locator. It is a pointer to locate resource in www (World
Wide Web). A resource can be anything from a simple text file to any other like images, file
directory etc.
The typical URL may look like
[Link]
The URL has the following parts:
● Protocol: In this case the protocol is HTTP, It can be HTTPS in some cases
● Hostname: Hostname represent the address of the machine on which resource is located, in
this case, [Link]
● Port Number: It is an optional attribute. If not specified then it returns -1. In the above case,
the port number is 80.
● Resource name: It is the name of a resource located on the given server that we want to see
You can learn more about the URL here.
The Class structure of the URL is as shown below:

48
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

public final class [Link] extends [Link]


The Following are constructors provided by the URL class.

Constructor Explanation

This constructor creates an object of URL class from given


public URL(String url )
string representation

public URL(String protocol,


This constructor creates an object of URL from the specified
String host, int port, String
protocol, host, port number, and file.
file)

This constructor creates an object of URL from the specified


public URL(String protocol,
protocol, port number, and file. The default port number is used
String host, String file)
in this case.

public URL(URL context, This constructor creates an instance of a URL by parsing the
String src) given src with the specified handler within a given context.

RMI ARCHITECTURE

RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in
one system (JVM) to access/invoke an object running on another JVM.

RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package [Link].

49
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Architecture of an RMI Application

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.

50
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● 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.

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.

51
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Marshalling and Unmarshalling

Whenever a client invokes a method that accepts parameters on a remote object, the parameters
are bundled into a message before being sent over the network. These parameters may be of
primitive type or objects. In case of primitive type, the parameters are put together and a header
is attached to it. In case the parameters are objects, then they are serialized. This process is
known as marshalling.

At the server side, the packed parameters are unbundled and then the required method is
invoked. This process is known as unmarshalling.

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).

The following illustration explains the entire process −

52
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Goals of RMI

Following are the goals of RMI −

● To minimize the complexity of the application.


● To preserve type safety.
● Distributed garbage collection.
● Minimize the difference between working with local and remote objects.

To write an RMI Java application, you would have to follow the steps given below −

● Define the remote interface


● Develop the implementation class (remote object)
● Develop the server program
● Develop the client program
● Compile the application

53
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● Execute the application


import [Link];

import [Link];

public class Client {

private Client() {}

public static void main(String[] args) {

try {

// Getting the registry

Registry registry = [Link](null);

// Looking up the registry for the remote object

Hello stub = (Hello) [Link]("Hello");

// Calling the remote method using the obtained object

[Link]();

// [Link]("Remote method invoked");

} catch (Exception e) {

[Link]("Client exception: " + [Link]());

[Link]();

54
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

}
Compiling the Application

To compile the application −

● Compile the Remote interface.


● Compile the implementation class.
● Compile the server program.
● Compile the client program.

CLIENT SERVER APPLICATION USING RMI.

What is RMI?
Remote Method Invocation (RMI) is a Java API that allows a program running
on one computer to invoke methods on an object located on another
computer. It provides a mechanism for distributed object communication.
Key Components of an RMI Application:
● Remote Interface: Defines the methods that can be invoked remotely. This interface
must extend [Link] and methods must throw [Link].
● Remote Implementation: A class that implements the remote interface. This class
contains the actual logic for the remote methods.
● Server: Creates an instance of the remote implementation, registers it with the RMI
registry, making it available for remote clients.
● Client: Looks up the remote object in the RMI registry and invokes methods on it.
● RMI Registry: A naming service that allows clients to find remote objects.
Steps to Create an RMI Application:

55
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Define the Remote Interface.

import [Link];

import [Link];

public interface MyRemoteInterface extends Remote {

String myRemoteMethod(String input) throws RemoteException;

Implement the Remote Interface.

import [Link];

import [Link];

public class MyRemoteImplementation extends UnicastRemoteObject


implements MyRemoteInterface {

public MyRemoteImplementation() throws RemoteException {

super();

56
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

@Override

public String myRemoteMethod(String input) throws RemoteException {

return "Server says: " + input;

Create the Server.

import [Link];

import [Link];

import [Link];

public class MyServer {

public static void main(String[] args) {

try {

MyRemoteImplementation obj = new MyRemoteImplementation();

Registry registry = [Link](1099); //Default port

[Link]("MyRemoteObject", obj);

[Link]("Server is ready");

} catch (Exception e) {

[Link]("Server exception: " + [Link]());

57
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

[Link]();

Create the Client.

import [Link];

import [Link];

public class MyClient {

public static void main(String[] args) {

try {

Registry registry = [Link]("localhost", 1099);

MyRemoteInterface stub = (MyRemoteInterface)


[Link]("MyRemoteObject");

String response = [Link]("Hello from client!");

[Link]("Response from server: " + response);

} catch (Exception e) {

[Link]("Client exception: " + [Link]());

[Link]();

58
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

59

You might also like