Java Unit 2 NOTES
Java Unit 2 NOTES
Client/Server Sockets – URL - UDP: Datagrams - [Link] package classes: Socket– ServerSocket -
InetAddress – URL – URL Connection - RMI Architecture - Client Server Application using
RMI.
NETWORKING BASICS
1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
1. sharing resources
2. centralize software management
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
2
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
● TCP
● FTP
● Telnet
● SMTP
● POP
Port Number
MAC Address
3
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Socket
4
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Socket class
Important methods
Method Description
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
6
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
import
[Link].
*;
import
[Link]
t.*;
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 {
8
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
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:
10
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
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
4. Raw Sockets
Characteristics:
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.
● 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
Common Operations
Creating Sockets:
Establishing Connections:
● Clients connect to servers using the server's IP address and port number.
● Servers accept incoming connections from clients.
14
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Closing Connections:
import [Link].*;
import [Link].*;
[Link]();
15
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
BufferedReaderin=newBufferedReader(newInputStreamReader([Link]()));
[Link]();
[Link]();
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].*;
[Link]("Server started");
[Link]("Client connected");
[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:
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].*;
[Link]("Connected to server");
[Link]("Hello Server");
[Link]();
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 ...
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
4. File Name or directory name: In this case, [Link] is the file name.
The [Link] class provides many methods. The important methods of URL class.
Method Description
21
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Method Description
//[Link]
import [Link].*;
import [Link].*;
22
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
try{
[Link]("Protocol: "+[Link]());
catch(Exception e)
[Link](e);
Output:
Protocol: http
Port Number: -1
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.
The openConnection() method of URL class returns the object of URLConnection class.
Syntax:
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.
import [Link].*;
import [Link].*;
try{
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);}
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.
The openConnection() method of URL class returns the object of URLConnection class.
Syntax:
HttpURLConnection huc=(HttpURLConnection)[Link]();
import [Link].*;
import [Link].*;
25
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
try{
HttpURLConnection huc=(HttpURLConnection)[Link]();
for(int i=1;i<=8;i++){
[Link]([Link](i)+" = "+[Link](i));
[Link]();
}catch(Exception e){[Link](e);}
Output:
Content-Type = text/html
Cache-Control = max-age=2592000
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.
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 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.
30
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
InetAddress
● Represents an IP address.
● Key methods:
o getLocalHost()
o getByName(String host)
o getHostAddress()
syntax:
31
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
[Link]([Link]());
Syntax:
Syntax:
32
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
DatagramSocket&DatagramPacket (UDP)
Syntax:
[Link](packet);
URL&URLConnection
Syntax:
InputStream in = [Link]();
33
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
HttpURLConnection
Syntax:
[Link]("GET");
Summary Table:
34
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
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
import [Link].*;
import [Link].*;
import [Link].*;
35
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
import [Link].*;
try {
[Link]("Starting server...");
Socket s = [Link]();
[Link]("Client connected!");
36
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
[Link]();
} catch (Exception e) {
Output:
Client-Side Programming
The below Java program demonstrate the working of client-side programming using
ServerSocket class.
// Java program demonstrates the
37
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
import [Link].*;
import [Link].*;
try {
// initializing Socket
[Link]());
// Message to be displayed
38
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
[Link]();
// Closing DataOutputStream
[Link]();
// Closing socket
[Link]();
catch (Exception e) {
[Link](e);
Output:
39
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Method Description
40
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Method Description
41
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Method Description
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.
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:
import [Link];
import [Link];
try {
} catch (UnknownHostException e) {
[Link]();
43
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
import [Link];
import [Link];
try {
} catch (UnknownHostException e) {
44
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
[Link]();
import [Link];
import [Link];
try {
[Link]([Link]());
45
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
} catch (UnknownHostException e) {
[Link]();
import [Link];
import [Link];
try {
46
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
} catch (UnknownHostException e) {
[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
Constructor Explanation
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
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
● 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
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).
52
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Goals of RMI
To write an RMI Java application, you would have to follow the steps given below −
53
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
import [Link];
private Client() {}
try {
[Link]();
} catch (Exception e) {
[Link]();
54
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
}
Compiling the Application
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
import [Link];
import [Link];
import [Link];
import [Link];
super();
56
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
@Override
import [Link];
import [Link];
import [Link];
try {
[Link]("MyRemoteObject", obj);
[Link]("Server is ready");
} catch (Exception e) {
57
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
[Link]();
import [Link];
import [Link];
try {
} catch (Exception e) {
[Link]();
58
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
59