0% found this document useful (0 votes)
9 views

UNIT 3

The document provides an overview of JDBC (Java Database Connectivity), detailing its purpose as a standard API for connecting Java applications to various databases. It covers JDBC architecture, classes, interfaces, and the steps required to develop JDBC applications, including connecting to a MySQL database. Additionally, it discusses creating databases and tables, working with database metadata, and the types of JDBC drivers available.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

UNIT 3

The document provides an overview of JDBC (Java Database Connectivity), detailing its purpose as a standard API for connecting Java applications to various databases. It covers JDBC architecture, classes, interfaces, and the steps required to develop JDBC applications, including connecting to a MySQL database. Additionally, it discusses creating databases and tables, working with database metadata, and the types of JDBC drivers available.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT-III

3.1 JDBC

3.1.1 INTRODUCTION
JDBC stands for Java Database Connectivity, which is a standard Java
API for database-independent connectivity between the Java programming
language and a wide range of databases.The JDBC library includes APIs for
each of the tasks mentioned below that are commonly associated with
database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an underlying database. Java
can be used to write different types of executables, such as −
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to
access a database, and take advantage of the stored data.JDBC provides the
same capabilities as ODBC, allowing Java programs to contain database-
independent code.

3.1.2 JDBC ARCHITECTURE


The JDBC API supports both two-tier and three-tier processing models
for database access but in general, JDBC Architecture consists of two layers

JDBC API − This provides the application-to-JDBC Manager connection.

JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to


provide transparent connectivity to heterogeneous databases. The JDBC
driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent
drivers connected to multiple heterogeneous databases. Following is the
architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application.

3.1.3 JDBC CLASSES AND INTERFACES


The JDBC API provides the following interfaces and classes :

DriverManager : This class manages a list of database drivers. Matches


connection requests from the java application with the proper database
driver using communication sub protocol. The first driver that recognizes a
certain subprotocol under JDBC will be used to establish a database
Connection.

Driver :This interface handles the communications with the database server.
You will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts
the details associated with working with Driver objects.
Connection:This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication
with database is through connection object only.

Statement :You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.

ResultSet:These objects hold data retrieved from a database after you


execute an SQL query using Statement objects. It acts as an iterator to allow
you to move through its data.

SQLException :This class handles any errors that occur in a database


application.

The JDBC 4.0 Packages

The java.sql and javax.sql are the primary packages for JDBC 4.0. This
is the latest JDBC version at the time of writing this tutorial. It offers the main
classes for interacting with your data sources. The new features in these
packages include changes in the following areas :

 Automatic database driver loading.


 Exception handling improvements.
 Enhanced BLOB/CLOB functionality.
 Connection and statement interface enhancements.
 National character set support.
 SQL ROWID access.
 SQL 2003 XML data type support.
 Annotations.
JDBC stands for Java Database Connectivity. JDBC is a Java API to
connect and execute the query with the database. It is a part of JavaSE (Java
Standard Edition). JDBC API uses JDBC drivers to connect with the database.
There are four Types of JDBC drivers:
JDBC Driver is a software component that enables java application to
interact with the database. There are 4 types of JDBC drivers:

 JDBC-ODBC bridge driver


 Native-API driver (partially java driver)
 Network Protocol driver (fully java driver)
 Thin driver (fully java driver)

3.1.4 DATABASE ACCESS WITH MYSQL


To connect Java application with the MySQL database, we need to
follow 5 following steps. In this example we are using MySql as the database.
So we need to know following information for the mysql database:

Driver class: The driver class for the mysql database


is com.mysql.jdbc.Driver.

Connection URL: The connection URL for the mysql database


is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the
database, localhost is the server name on which mysql is running, we may
also use IP address, 3306 is the port number and sonoo is the database
name. We may use any database, in such case, we need to replace the
sonoo with our database name.

Username: The default username for the mysql database is root.

Password: It is the password given by the user at the time of installing the
mysql database. In this example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating
table, we need to create database first.

create database sonoo;

use sonoo;

create table emp(id int(10),name varchar(40),age int(3));


Example to Connect Java Application with mysql database

In this example, sonoo is the database name, root is the username and
password both.

import java.sql.*;

class MysqlCon{

public static void main(String args[]){

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(

"jdbc:mysql://localhost:3306/sonoo","root","root");

//here sonoo is database name, root is username and password

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();

}catch(Exception e){ System.out.println(e);}

The above example will fetch all the records of emp table.

Two ways to load the jar file:


Paste the mysqlconnector.jar file in jre/lib/ext folder

Set class path

Paste the mysqlconnector.jar file in JRE/lib/ext folder:

Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the


jar file here.

Set class path:

There are two ways to set the classpath:

 temporary
 permanent
How to set the temporary classpath

open command prompt and write:

C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

How to set the permanent classpath

Go to environment variable then click on new tab. In variable name


write classpath and in variable value paste the path to the
mysqlconnector.jar file by appending mysqlconnector.jar;.; as C:\folder\
mysql-connector-java-5.0.8-bin.jar;.;

3.1.5 STEPS IN DEVELOPING JDBC APPLICATION


There are 5 steps to connect any java application with the database
using JDBC. These steps are as follows:

 Register the Driver class


 Create connection
 Create statement
 Execute queries
 Close connection
Register the driver class
The forName() method of Class class is used to register the driver
class. This method is used to dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

Class.forName("oracle.jdbc.driver.OracleDriver");

Create the connection object

The getConnection() method of DriverManager class is used to


establish connection with the database.

Syntax of getConnection() method

public static Connection getConnection(String url)throws SQLException

public static Connection getConnection(String url,String name,String


password) throws SQLException

Example to establish connection with the Oracle database

Connection con=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe","system","password");

Create the Statement object

The createStatement() method of Connection interface is used to


create statement. The object of statement is responsible to execute queries
with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException


Example to create the statement object

Statement stmt=con.createStatement();

Execute the query

The executeQuery() method of Statement interface is used to execute


queries to the database. This method returns the object of ResultSet that can
be used to get all the records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException

Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2));

Close the connection object

By closing connection object statement and ResultSet will be closed


automatically. The close() method of Connection interface is used to close
the connection.

Syntax of close() method

public void close()throws SQLException

Example to close connection

con.close();

Since Java 7, JDBC has ability to use try-with-resources statement to


automatically close resources of type Connection, ResultSet, and
Statement.It avoids explicit connection closing .
3.1.6 CREATING A NEW DATABASE AND TABLE WITH JDBC
MySQL is a free and open source database management system. You
need to use sql commands to create database. You also need to login as
mysql root user account. To create a database and set up tables for the
same use the following sql commands:

CREATE DATABASE – create the database. To use this statement, you need
the CREATE privilege for the database.

CREATE TABLE :create the table. You must have the CREATE privilege for
the table.

INSERT –:To add/insert data to table i.e. inserts new rows into an existing
table.

Procedure for creating a database and a sample table

Login as the mysql root user to create database:


$ mysql -u root -p
Sample outputs: mysql>

Add a database called STUDENTS, enter:


Mysql> CREATE DATABASE students;

Now, database is created. Use a database with use command, type:


mysql> USE students;

The following steps are required to create a new Database using JDBC
application −

Import the packages − Requires that you include the packages containing
the JDBC classes needed for database programming. Most often, using
import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection()
method to create a Connection object, which represents a physical
connection with the database server.

 To create a new database, you need not give any database name while
preparing database URL as mentioned in the below example.
Execute a query − Requires using an object of type Statement for building
and submitting an SQL statement to the database.

Clean up the environment . try with resources automatically closes the


resources.

Sample Code

Copy and paste the following example in JDBCExample.java, compile and run
as follows −

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class JDBCExample {

static final String DB_URL = "jdbc:mysql://localhost/";


static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
Statement stmt = conn.createStatement();
){
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException e) {
e.printStackTrace();
} }
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Database created successfully...
C:\>

3.1.7 WORKING WITH DATABASE METADATA


Generally, Data about data is known as metadata. The
DatabaseMetaData interface provides methods to get information about
the database you have connected with like, database name, database driver
version, maximum column length etc...

Following are some methods of DatabaseMetaData class.

Method Description

getDriverName() Retrieves the name of the current JDBC driver

getDriverVersion() Retrieves the version of the current JDBC driver

getUserName() Retrieves the user name.

getDatabaseProductNam Retrieves the name of the current database.


e()

getDatabaseProductVersi Retrieves the version of the current database.


on()

getNumericFunctions() Retrieves the list of the numeric functions


available with this database.

getStringFunctions() Retrieves the list of the numeric functions


available with this database.

getSystemFunctions() Retrieves the list of the system functions


available with this database.

getTimeDateFunctions() Retrieves the list of the time and date functions


available with this database.

getURL() Retrieves the URL for the current database.

supportsSavepoints() Verifies weather the current database supports


save points

supportsStoredProcedure Verifies weather the current database supports


s() stored procedures.

supportsTransactions() Verifies weather the current database supports


transactions.

Example

Following example demonstrates the usage of DatabaseMetaData class.


import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
public class DatabaseMetadataExample {
public static void main(String args[])throws Exception {
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root",
"password");
System.out.println("Connection established......");
//Creating the DatabaseMetaData object
DatabaseMetaData dbMetadata = con.getMetaData();
//invoke the supportsBatchUpdates() method.
boolean bool = dbMetadata.supportsBatchUpdates();
if(bool) {
System.out.println("Underlying database supports batch updates");
} else {
System.out.println("Underlying database doesnt supports batch
updates");
}
//Retrieving the driver name
System.out.println(dbMetadata.getDriverName());
//Retrieving the driver version
System.out.println(dbMetadata.getDriverVersion());
//Retrieving the user name
System.out.println(dbMetadata.getUserName());
//Retrieving the URL
System.out.println(dbMetadata.getURL());
//Retrieving the list of numeric functions
System.out.println("Numeric functions:
"+dbMetadata.getNumericFunctions());
System.out.println("");
//Retrieving the list of String functions
System.out.println("String functions:
"+dbMetadata.getStringFunctions());
System.out.println("");
//Retrieving the list of system functions
System.out.println("System functions:
"+dbMetadata.getSystemFunctions());
System.out.println("");
//Retrieving the list of time and date functions
System.out.println("Time and Date funtions:
"+dbMetadata.getTimeDateFunctions());
}}
Output
Connection established......

Underlying database supports batch updates

MySQL-AB JDBC Driver

mysql-connector-java-5.1.12 ( Revision: ${bzr.revision-id} )

root@localhost

jdbc:mysql://localhost/sampleDB

Numeric functions:

ABS,ACOS,ASIN,ATAN,ATAN2,BIT_COUNT,CEILING,COS,COT,DEGREES,EXP,FL
OOR,LOG,LOG10,MAX

,MIN,MOD,PI,POW,POWER,RADIANS,RAND,ROUND,SIN,SQRT,TAN,TRUNCATE

String functions:

ASCII,BIN,BIT_LENGTH,CHAR,CHARACTER_LENGTH,CHAR_LENGTH,CONCAT,C
ONCAT_WS,CONV,ELT,E

XPORT_SET,FIELD,FIND_IN_SET,HEX,INSERT,INSTR,LCASE,LEFT,LENGTH,LOAD
_FILE,LOCATE,LO

CATE,LOWER,LPAD,LTRIM,MAKE_SET,MATCH,MID,OCT,OCTET_LENGTH,ORD,P
OSITION,QUOTE,REPEA
T,REPLACE,REVERSE,RIGHT,RPAD,RTRIM,SOUNDEX,SPACE,STRCMP,SUBSTRIN
G,SUBSTRING,SUBSTR

ING,SUBSTRING,SUBSTRING_INDEX,TRIM,UCASE,UPPER

System functions:

DATABASE,USER,SYSTEM_USER,SESSION_USER,PASSWORD,ENCRYPT,LAST_I
NSERT_ID,VERSION

Time and Date funtions:

DAYOFWEEK,WEEKDAY,DAYOFMONTH,DAYOFYEAR,MONTH,DAYNAME,MONTH
NAME,QUARTER,WEEK,YEAR,H

OUR,MINUTE,SECOND,PERIOD_ADD,PERIOD_DIFF,TO_DAYS,FROM_DAYS,DAT
E_FORMAT,TIME_FORMAT

,CURDATE,CURRENT_DATE,CURTIME,CURRENT_TIME,NOW,SYSDATE,CURREN
T_TIMESTAMP,UNIX_TIME

STAMP,FROM_UNIXTIME,SEC_TO_TIME,TIME_TO_SEC3.9 INTRODUCTION TO

3.2 JAVA NETWORKING BASICS OF NETWORKING


Java Networking is a notion of connecting two or more computing
devices together to share the resources. Java program communicates over
the network at the application layer. java.net package is useful for all the
Java networking classes and interfaces.

The java.net package provides support for two protocols. They are as
follows:

TCP − Transmission Control Protocol allows reliable communication between


two applications. TCP is typically used over the Internet Protocol, which is
referred to as TCP/IP.
UDP − User Datagram Protocol is a connection-less protocol that allows
packets of data to be transmitted between applications.

3.2. NETWORKING IN JAVA


The widely used Java networking terminologies used are as follows:

 IP Address
 Protocol
 Port Number
 MAC Address
 Connection-oriented and connection-less protocol
 Socket
Now let’s get into the details of each of these methods.

IP Address

The IP address is a unique number assigned to a node of a network e.g.


192.168.0.1. It is composed of octets that range from 0 to 255.

Protocol

A protocol is a set of rules followed for communication. For example:

TCP , FTP Telnet ,SMTP,POP etc.

Port Number

The port number uniquely identifies different applications. It acts as a


communication endpoint between applications. To communicate between
two applications, the port number is used along with an IP Address.

MAC Address

A MAC address is basically a hardware identification number which


uniquely identifies each device on a network. For example, an Ethernet card
may have a MAC address of 00:0d:83:b1:c0:8e.

Connection-oriented and connection-less protocol


In the connection-oriented protocol, acknowledgment is sent by the
receiver. So it is reliable but slow. The example of a connection-oriented
protocol is TCP. But, in the connection-less protocol, acknowledgment is not
sent by the receiver. So it is not reliable but fast. The example of a
connection-less protocol is UDP.

Socket:A socket in Java is one endpoint of a two-way communication link


between two programs running on the network. A socket is bound to a port
number so that the TCP layer can identify the application that data is
destined to be sent to.

3.3 SOCKET PROGRAMMING USING TCP/IP


TCP is a Network Protocol which stands for Transfer Control Protocol,
that allows well founded communication between applications. TCP is
consistently used over the Internet Protocol, and that is why referred as
TCP/IP. The communication mechanism between two systems, using TCP,
can be established using Sockets and is known as Socket Programming..

Mechanism for Socket Programming

A client creates a socket at it’s end of transmission, and strive to


connect the socket to server. When a connection is established, server
creates a socket at it’s end and, client and server can now ready
communicate through writing and reading methods. Following is the
elaborated procedure of what happens when a TCP connection is
established:

An attempt is made, for connecting the client to the server using the
specified IP address and port number. If attempt is successful, client is
provided with a Socket that is capable of communicating to the respective
server, with write and read methods. If unsuccessful, desired exception is
raised.
Once the communication is completed, terminate the sockets on both, the
server and the client side.

Client Side Programming

For the Client machine, we need to now establish the socket


connection. Socket Connection is when the two machines have information
about each other’s network location (IP Address) and the TCP port.

Connection:

Socket socket = new Socket(IP Address, port number);

//IP Address of the server

//TCP port Number on which the server is listening

Communication

The communication is held using the output and input streams. These
streams are responsible for transmitting the information in the form of byte
array. An object can also be transmitted through these streams, but it needs
to be serialized before transmitting and deserialized after it has been
received. Input and output streams are made available through socket
instances.

Terminating Connection:

The socket connection needs to be terminated explicitly once the


communication is fulfilled.

Implementation:

Below is the client side implementation of socket programming in java.

import java.io.*;
import java.net.*;
class Client
{
public static void main(String data[])
{
//data is taken as command line argument
String ipAddress=data[0];
int portNumber=Integer.parseInt(data[1]);
int rollNumber=Integer.parseInt(data[2]);
String name=data[3];
String gender=data[4];
String request=rollNumber+”,”+name+”,”+gender+”#”;
//”#” acts as a terminator
try
{
Socket socket=new Socket(ipAddress , portNumber);
// Socket is initialized and attempt is made for connecting to the server
// Declaring other properties and streams
OutputStream outputStream;
OutputStreamWriter outputStreamWriter;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuffer stringBuffer;
String response;
int x;
// retrieving output Stream and its writer, for sending request or
acknowledgement
outputStream=socket.getOutputStream();
outputStreamWriter=new OutputStreamWriter(outputStream);
outputStreamWriter.write(request);
outputStreamWriter.flush(); // request is sent
// retrieving input stream and its reader, for receiving acknowledgement or
response
inputStream=socket.getInputStream();
inputStreamReader=new InputStreamReader(inputStream);
stringBuffer=new StringBuffer();
while(true)
{
x=inputStreamReader.read();
if(x==’#’ || x==-1) break; // reads till the terminator
stringBuffer.append((char)x);
}
response=stringBuffer.toString();
System.out.println(response);
socket.close(); //closing the connection
}catch(Exception exception)
{
// Raised in case, connection is refused or some other technical issue
System.out.println(exception);
}}
}
Server Side Programming
For the server side programming, a ServerSocket is required, that will
wait for the client in the listening mode, on a particular TCP port. This
ServerSocket holds until a Client Socket is connected successfully. As soon
as the client is connected, another Socket comes to the existence that will
enable data sharing between the respective client and server.

Creating ServerSocket:

The ServerSocket is instantiated on a specific port number. Then, the


server starts listening for the client requests coming in for that port number.
The accept method waits until a client connects to the server. After
successful connection, accept returns a Socket that will facilitate the
communication.

Communication:

For data transfer, getOutputStream method is used to send the output


through the socket and input is received using getInputStream method. The
Server keeps receiving messages until the it receives the terminator.

Terminating Connection:

Once the response is sent, the socket, along with the input and output
streams needs to be closed explicitly.

Implementation:

The Server implemented below is a multi-threaded server, so it can


listen to multiple clients without any interruption. This works efficiently
because, after establishing the connection, the server diverts the request,
along with the respective socket, to another Thread or another Request
Processor..

import java.io.*;
import java.net.*;
class RequestProcessor extends Thread //for multi-threaded server
{
private Socket socket;
RequestProcessor(Socket socket)
{
this.socket=socket;
start(); // will load the run method
}
public void run()
{
try
{
//Declaring properties and streams
OutputStream outputStream;
OutputStreamWriter outputStreamWriter;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuffer stringBuffer;
String response;
String request;
int x;
int temp1,temp2;
String part1,part2,part3;
int rollNumber;
String name;
String gender;
//getting input stream and its reader, for reading request or
acknowledgement
inputStream=socket.getInputStream();
inputStreamReader=new InputStreamReader(inputStream);
stringBuffer=new StringBuffer();
while(true)
{
x=inputStreamReader.read();
if(x=='#' || x==-1) break; //reads until terminator
stringBuffer.append((char)x);
}
request=stringBuffer.toString();
System.out.println("Request : "+request);
//parsing and extracting Request data
temp1=request.indexOf(",");
temp2=request.indexOf(",",temp1+1);
part1=request.substring(0,temp1);
part2=request.substring(temp1+1,temp2);
part3=request.substring(temp2+1);
rollNumber=Integer.parseInt(part1);
name=part2;
gender=part3;
System.out.println("Roll number : "+rollNumber);
System.out.println("Name : "+name);
System.out.println("Gender : "+gender);
// handle data
//sending response
response="Data saved#";
//get output stream and its writer, for sending response or acknowledgement
outputStream=socket.getOutputStream();
outputStreamWriter=new OutputStreamWriter(outputStream);
outputStreamWriter.write(response);
outputStreamWriter.flush(); // response sent
System.out.println("Response sent");
socket.close(); //terminating connection
}catch(Exception exception)
{
System.out.println(exception);
}
}}
class Server
{
private ServerSocket serverSocket;
private int portNumber;
Server(int portNumber)
{
this.portNumber=portNumber;
try
{
//Initiating ServerSocket with TCP port
serverSocket=new ServerSocket(this.portNumber);
startListening();
}catch(Exception e)
{
System.out.println(e);
System.exit(0);
}}
private void startListening()
{
try
{
Socket socket;
while(true)
{
System.out.println("Server is listening on port : "+this.portNumber);
socket=serverSocket.accept(); // server is in listening mode
System.out.println("Request arrived..");
// diverting the request to processor with the socket reference
new RequestProcessor(socket);
}
}catch(Exception e)
{
System.out.println(e);
}
} public static void main(String data[])
{
int portNumber=Integer.parseInt(data[0]);
Server server=new Server(portNumber);
}}
Execution:
To run, compile the server and client code. First, start server in prompt like
this:

Compile and execute the client in another prompt like this:

After the data is sent from client, server prompt will look like this:

3.4 SOCKET PROGRAMMING USING UDP-URL


UDP is quite different from the more common TCP. But before
considering the surface level disadvantages of UDP, it's important to
understand that the lack of overhead can make it significantly faster than
TCP.
Apart from speed, we also need to remember that some kinds of
communication do not require the reliability of TCP but value low latency
instead. The video is a good example of an application that might benefit
from running over UDP instead of TCP.

UDP Sockets

The UDP socket communication between a server and a client consists


of several phases as follows.

socket() - Firstly a socket is defined in both server and client. This need not
happen at the same time. For the explanation to be comprehensive, I will be
discussing the actions of both server and client in each stage.

bind() - Defined socket is assigned an id and a port in the running machine.


This is optional for the client socket. This is because even if the client socket
is not bound, it will automatically happen whenever the client initiates
connecting to the server.

recvfrom() -After binding to a port in the machine, the server socket waits
for a connection from a client socket. In the meantime, further execution of
the current thread is halt (blocked) until the server socket receives a
connection. This is the same for the client socket when waiting for a server
response.
sendto() - After connecting with a client, the server socket sends data to
the client. This same method is used by the client socket to make a
connection request to the server.

close() - After successful data exchange, both sockets are closed i.e. system
resources allocated for the sockets are released.

UDP Socket Communication

The DatagramPacket and DatagramSocket classes in Java support


utilizing UDP socket communication at the application level. Let’s write a
simple server and a client in Java that communicates with each other using
UDP socket communication.

In this example, the socket server receives data of type String from the client
and sends the capitalized string back to the client.

Since we are aware of the stages of UDP socket communication, I have


only put comments in both Java programs to explain the code instead of
using long paragraphs. This way will also help you to quickly understand the
code while reading the code.

Building the UDP socket server

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPServer{
public final static int SERVICE_PORT=50001;
public static void main(String[] args) throws IOException{
try{
DatagramSocket serverSocket = new DatagramSocket(SERVICE_PORT);
byte[] receivingDataBuffer = new byte[1024];
byte[] sendingDataBuffer = new byte[1024];
DatagramPacket inputPacket = new DatagramPacket(receivingDataBuffer,
receivingDataBuffer.length);
System.out.println("Waiting for a client to connect...");
serverSocket.receive(inputPacket);
String receivedData = new String(inputPacket.getData());
System.out.println("Sent from the client: "+receivedData);
sendingDataBuffer = receivedData.toUpperCase().getBytes();
InetAddress senderAddress = inputPacket.getAddress();
int senderPort = inputPacket.getPort();
DatagramPacket outputPacket = new DatagramPacket(sendingDataBuffer,
sendingDataBuffer.length,senderAddress,senderPort);
serverSocket.send(outputPacket);
serverSocket.close();
}
catch (SocketException e){
e.printStackTrace();
}}
}
Creating the UDP socket client:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPClient{
public final static int SERVICE_PORT = 50001;
public static void main(String[] args) throws IOException{
try{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendingDataBuffer = new byte[1024];
byte[] receivingDataBuffer = new byte[1024];
String sentence = "Hello from UDP client";
sendingDataBuffer = sentence.getBytes();
DatagramPacket sendingPacket = new
DatagramPacket(sendingDataBuffer,sendingDataBuffer.length,IPAddress,
SERVICE_PORT);
clientSocket.send(sendingPacket);
DatagramPacket receivingPacket = new
DatagramPacket(receivingDataBuffer,receivingDataBuffer.length);
clientSocket.receive(receivingPacket);
String receivedData = new String(receivingPacket.getData());
System.out.println("Sent from the server: "+receivedData);
clientSocket.close();
}
catch(SocketException e) {
e.printStackTrace();
}
}}
UDPServer.java

Waiting for a client to connect...

Sent from the client: Hello from UDP client

UDPClient.java

sent from the server: HELLO FROM UDP CLIENT

3.5 URL AND INET ADDRESS CLASSES


The URL class is the gateway to any of the resource available on the
internet. A Class URL represents a Uniform Resource Locator, which is a
pointer to a “resource” on the World Wide Web. A resource can point to a
simple file or directory, or it can refer to a more complicated object, such as
a query to a database or to a search engine.
Components of a URL:-

A URL can have many forms. The most general however follows three-
components system-
Protocol: HTTP is the protocol here

Hostname: Name of the machine on which the resource lives.


File Name: The path name to the file on the machine.
Port Number: Port number to which to connect (typically optional).
constructors for URL class:
URL(String address) throws MalformedURLException: It creates a URL object
from the specified String.
URL(String protocol, String host, String file): Creates a URL object from
the specified protocol, host, and file name.
URL(String protocol, String host, int port, String file): Creates a URL object
from protocol, host, port and file name.
URL(URL context, String spec): Creates a URL object by parsing the given
spec in the given context.
URL(String protocol, String host, int port, String file, URLStreamHandler
handler):
Creates a URL object from the specified protocol, host, port number, file, and
handler.
URL(URL context, String spec, URLStreamHandler handler):

Creates a URL by parsing the given spec with the specified handler within a
specified context.
Program:
import java.net.MalformedURLException;
import java.net.URL;
public class URLclass1
{
public static void main(String[] args)
throws MalformedURLException
{
URL url1 = new URL("https://www.google.co.in/?gfe_rd=cr&ei=ptYq" +
"WK26I4fT8gfth6CACg#q=geeks+for+geeks+java");
URL url2 = new URL("http", "www.geeksforgeeks.org", kjsxdfef "/jvm-works-
jvm-architecture/");
URL url3 = new URL("https://www.google.co.in/search?"+
"q=gnu&rlz=1C1CHZL_enIN71" +"4IN715&oq=gnu&aqs=chrome..69i57j6" +
"9i60l5.653j0j7&sourceid=chrome&ie=UTF" +"-
8#q=geeks+for+geeks+java");
System.out.println(url1.toString());
System.out.println(url2.toString());
System.out.println();
System.out.println("Different components of the URL3-");
System.out.println("Protocol:- " + url3.getProtocol());
System.out.println("Hostname:- " + url3.getHost());
System.out.println("Default port:- " +url3.getDefaultPort());
System.out.println("Query:- " + url3.getQuery());
System.out.println("Path:- " + url3.getPath());
System.out.println("File:- " + url3.getFile());
System.out.println("Reference:- " + url3.getRef());
}
}
Output:
https://www.google.co.in/?
gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=geeks+for+geeks+java
https://www.geeksforgeeks.org/jvm-works-jvm-architecture/
Different components of the URL3-
Protocol:- https
Hostname:- www.google.co.in
Default port:- 443
Query:-
q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.6
53j0j7&sourceid=chrome&ie=UTF-8
Path:- /search

File:- /search?
q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.6
53j0j7&sourceid=chrome&ie=UTF-8
Reference:- q=geeks+for+geeks+java
INET ADDRESS CLASS
The java.net.InetAddress class provides methods to get the IP address
of any hostname. An IP address is represented by 32-bit or 128-bit unsigned
number. InetAddress can handle both IPv4 and IPv6 addresses.
There are 2 types of addresses :

Unicast — An identifier for a single interface.

Multicast — An identifier for a set of interfaces.

InetAddress – Factory Methods

The InetAddress class is used to encapsulate both, the numerical IP


address and the domain name for that address. The InetAddressclass has no
visible constructors. The InetAddress class has the inability to create objects
directly, hence factory methods are used for the purpose. Factory Methods
are static methods in a class that return an object of that class.

Methods

static InetAddress getLocalHost() throws UnknownHostException:


This method returns the instance of InetAddress containing the local
hostname and address.

public static InetAddress getByName( String host ) throws


UnknownHostException :This method returns the instance of
InetAddress containing LocalHost IP and name.
static InetAddress[] getAllByName( String hostName ) throws
UnknownHostException: This method returns the array of the instance
of InetAddress class which contains IP addresses.
static InetAddress getByAddress( byte IPAddress[] ) throws
UnknownHostException: This method returns an InetAddress object
created from the raw IP address.
static InetAddress getByAddress( String hostName, byte
IPAddress[] ) throws UnknownHostException: This method creates
and returns an InetAddress based on the provided hostname and IP address.
PROGRAM:

main(String[] args)
throws UnknownHostException
{
InetAddress address1 = InetAddress.getLocalHost();
System.out.println("InetAddress of Local Host : " + address1);
InetAddress address2 = InetAddress.getByName("45.22.30.39");
System.out.println("InetAddress of Named Host : " + address2);
InetAddress address3[]= InetAddress.getAllByName("172.19.25.29");
for (int i = 0; i < address3.length; i++) {
System.out.println( "ALL InetAddresses of Named Host : "+ address3[i]);
}
byte IPAddress[] = { 125, 0, 0, 1 };
InetAddress address4 = InetAddress.getByAddress(IPAddress);
System.out.println( "InetAddresses of Host with specified IP Address : " +
address4);
byte[] IPAddress2= { 105, 22, (byte)223, (byte)186 };

InetAddress address5 = InetAddress.getByAddress("gfg.com", IPAddress2);

System.out.println( "InetAddresses of Host with specified IP Address and


hostname : " + address5);
}}

Output:

InetAddress of Local Host : localhost/127.0.0.1

InetAddress of Named Host : /45.22.30.39

ALL InetAddresses of Named Host : /172.19.25.29

InetAddresses of Host with specified IP Address : /125.0.0.1

InetAddresses of Host with specified IP Address and host

InetAddress — Instance Methods :

InetAddress class has plenty of instance methods that can be called


using the object. The instance methods are –

equals(Object obj) This function compares this object against the


specified object.getAddress(): This method returns the raw IP address
of this InetAddress object, in bytes.

getCanonicalHostName(): This method returns the fully qualified domain


name for this IP address.

getHostAddress(): This method gets the IP address in string form.

getHostName(): This method returns the host name for this IP


address.

hashCode(): This method gets a hashcode for this IP address.

AnyLocalAddress() :This method utility routine to check if the


InetAddress is an unpredictable address.

isLinkLocalAddress(): This method utility routine to check if the


address is not linked to local unicast address.
isLoopbackAddress(): This method used to check if the InetAddress
represents a loopback address.

isMCGlobal(): This method utility routine check if this address has a


multicast address of global scope.

isMCLinkLocal(): This method utility routine check if this address has a


multicast address of link-local scope.

isMCNodeLocal(): This method utility routine check if the multicast


address has node scope.

isMCOrgLocal(): This method utility routine check if the multicast


address has an organization scope.

isMCSiteLocal(): This method utility routine check if the multicast


address has site scope.

isMulticastAddress(): This method checks whether the site has


multiple servers.

isReachable(int timeout) This method tests whether that address is


reachable.

isReachable(NetworkInterface netif, int ttl, int timeout) This


method tests whether that address is reachable.

isSiteLocalAddress(): This method utility routine check if the


InetAddress is a site-local address.

toString(): This method converts and returns an IP address in string


form.

PROGRAM:

import java.io.*;
import java.net.*;
import java.util.*;
class GFG {
public static void main(String[] args) throws UnknownHostException
{ InetAddress address1 = InetAddress.getByName("45.22.30.39");
InetAddress address2 = InetAddress.getByName("45.22.30.39");
InetAddress address = InetAddress.getByName("172.19.25.29");
System.out.println("Is Address-1 equals to Address-2? : " +
address1.equals(address2));
System.out.println( "Is Address-1 equals to Address-3? : "+
address1.equals(address3));
System.out.println("IP Address : "+ address1.getHostAddress());
System.out.println("Host Name for this IP Address : " +
address1.getHostName());
System.out.println("IP Address in bytes : " + address1.getAddress());
System.out.println("Is this Address Multicast? : " +
address1.isMulticastAddress());
System.out.println("Address in string form : " + address1.toString());
System.out.println( "Fully qualified domain name for this IP address : "+
address1.getCanonicalHostName());
System.out.println("Hashcode for this IP address : "+ address1.hashCode());
System.out.println("Is the InetAddress an unpredictable address? : "+
address1.isAnyLocalAddress());
} }
Output:

Is Address-1 equals to Address-2? : true

Is Address-1 equals to Address-3? : false


IP Address : 45.22.30.39
Host Name for this IP Address : 45.22.30.39
IP Address in bytes : [B@579bb367
Is this Address Multicast? : false
Address in string form : 45.22.30.39/45.22.30.39
Fully qualified domain name for this IP address : 45.22.30.39
Hashcode for this IP address : 756424231
Is the InetAddress an unpredictable address? : false

You might also like