Bachelor of Computer Applications
Course Code BCA-S302T
Course Name Java Programming and Dynamic Webpage Design
Unit 3
Networking
Java has been associated with Internet programming. Java became the premier
language for network programming are the classes defined in the [Link] package. Java
has also provided enhanced networking support for HTTP clients in the [Link]
package in a module by the same name. Called the HTTP Client API, it further solidifies
Java’s networking capabilities.
Networking Basics
At the core of Java’s networking support is the concept of a socket. A socket identifies
an endpoint in a network. The socket paradigm was part of the 4.2BSD Berkeley UNIX
release in the early 1980s. Because of this, the term Berkeley socket is also used.
Sockets are at the foundation of modern networking because a socket allows a single
computer to serve many different clients at once, as well as to serve many different
types of information. This is accomplished through the use of a port, which is a
numbered socket on a particular machine. A server process is said to "listen" to a port
until a client connects to it. A server is allowed to accept multiple clients connected to
the same port number, although each session is unique. To manage multiple client
connections, a server process must be multithreaded or have some other means of
multiplexing the simultaneous I/O.
Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level
routing protocol that breaks data into small packets and sends them to an address
across a network, which does not guarantee to deliver said packets to the destination.
Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly
string together these packets, sorting and retransmitting them as necessary to reliably
transmit data. A third protocol, User Datagram Protocol (UDP), sits next to TCP and can
be used directly to support fast, connectionless, unreliable transport of packets. Once a
connection has been established, a higher-level protocol ensues, which is dependent on
which port you are using. TCP/IP reserves the lower 1,024 ports for specific protocols.
HTTP is the protocol that web browsers and servers use to transfer hypertext pages and
images. It is a quite simple protocol for a basic page-browsing web server. Here’s how it
works. When a client requests a file from an HTTP server, an action known as a hit, it
simply sends the name of the file in a special format to a predefined port and reads back
the contents of the file. The server also responds with a status code to tell the client
whether or not the request can be fulfilled.
The [Link] Networking Classes and Interfaces
The [Link] package contains Java’s original networking features, which have been
available since version 1.0. It supports TCP/IP both by extending the already established
stream I/O interface and by adding the features required to build I/O objects across the
network. Java supports both the TCP and UDP protocol families. TCP is used for reliable
stream-based I/O across the network. UDP supports a simpler, hence faster, point-to-
point datagram-oriented model. The classes contained in the [Link] package are
shown here:
Class Description
InetAddress Represents an IP address (IPv4 or IPv6).
Socket Used for client-side TCP connections.
ServerSocket Used for server-side TCP connections.
DatagramSocket Used for UDP (connectionless) communication.
DatagramPacket Represents a packet of data for UDP communication.
URL Represents a Uniform Resource Locator (e.g., a web address).
URLConnection Represents a communication link to a URL.
HttpURLConnection Subclass of URLConnection for HTTP-specific features.
Represents a Uniform Resource Identifier (more general than
URI
URL).
URLDecoder /
Used for encoding/decoding URL parameters.
URLEncoder
Common Interfaces in [Link]:
Interface Description
ContentHandlerFactory Creates content handlers for different MIME types.
FileNameMap Maps file extensions to MIME types.
SocketImplFactory Creates custom SocketImpl objects.
URLStreamHandlerFactory Creates stream handlers for different protocols.
CookiePolicy Defines rules for accepting/rejecting cookies.
CookieStore Stores cookies for HTTP clients.
ResponseCache Allows caching of URL responses.
Example
import [Link].*;
class InetAddressTest{
public static void main(String[]args) throws UnknownHostException
{
InetAddress Address=[Link]();
[Link](Address);
Address=[Link]("[Link]");
[Link](Address);
}
TCP/IP Client Sockets
TCP/IP sockets are used to implement reliable, bidirectional, persistent, point to-point,
stream-based connections between hosts on the Internet. A socket can be used to
connect Java’s I/O system to other programs that may reside either on the local
machine or on any other machine on the Internet, subject to security constraints.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for
clients. The ServerSocket class is designed to be a "listener," which waits for clients to
connect before doing anything. Thus, ServerSocket is for servers. The Socket class is for
clients. It is designed to connect to server sockets and initiate protocol exchanges.
Because client sockets are the most commonly used by Java applications.
The creation of a Socket object implicitly establishes a connection between the client
and server. Here are two constructors used to create client sockets
Socket(String hostname,int port) Create a socket connected to the named
throws host and port.
UnknownHostException,IOException
Socket(InetAddress ipAddress,int port) Create a socket using preexisting
throws IOException InetAddress object and port.
Socket defines several instance methods. For example, a Socket can be examined at any
time for the address and port information associated with it, by use of the following
methods:
InetAddress getInetAddress() Return the InetAddress associated with
the socket object. It returns null if the
socket is not connected.
Int getPort() Returns the remote port to which the
invoking Socket object is [Link]
returns 0 when the Socket object is not
connected.
Int getLocalPort() Return the local port to which the
invoking Socket object is bound. It returns
-1 if the Socket is not bound.
You can gain access to the input and output streams associated with a Socket by use of
the getInputStream( ) and getOuptutStream( ) methods, as shown here. Each can throw
an IOException if the socket has been invalidated by a loss of connection. These streams
are used exactly like the I/O streams.
InputSream getInputStream() throws Return the input stream associated with
IOException the invoking Socket.
OutputStream getOutputStream() throws Return the Output stream associated with
IOException the invoking Socket.
Example
class SocketExample {
public static void main(String[] args) {
try {
Socket socket = new Socket("[Link]", 80);
[Link]("Connected to: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Local Port: " + [Link]());
[Link](5000); // 5 seconds timeout
// Close the socket
[Link]();
[Link]("Is socket closed? " + [Link]());
} catch (IOException e) {
[Link]();
}
}
}
Datagrams
TCP/IP-style networking is appropriate for most networking needs. It provides a
serialized, predictable, reliable stream of packet data. This is not without its cost,
however. TCP includes many complicated algorithms for dealing with congestion control
on crowded networks, as well as pessimistic expectations about packet loss. This leads
to a somewhat inefficient way to transport data. Datagrams provide an alternative.
Datagrams are bundles of information passed between machines. They are somewhat
like a hard throw from a well-trained but blindfolded catcher to the third baseman.
Once the datagram has been released to its intended target, there is no assurance that
it will arrive or even that someone will be there to catch it. Likewise, when the datagram
is received, there is no assurance that it hasn’t been damaged in transit or that whoever
sent it is still there to receive a response. Java implements datagrams on top of the UDP
protocol by using two classes: the DatagramPacket object is the data container, while
the DatagramSocket is the mechanism used to send or receive the DatagramPackets.
DatagramSocket
DatagramSocket defines four public constructors. They are shown here:
DatagramSocket( ) throws SocketException
DatagramSocket(int port) throws SocketException
DatagramSocket(int port, InetAddress ipAddress) throws SocketException
DatagramSocket(SocketAddress address) throws SocketException
Method Description
send(DatagramPacket p) Sends a UDP packet to the destination.
Receives a UDP packet. (Blocks until a packet
receive(DatagramPacket p)
is received)
close() Closes the socket.
Returns the port number the socket is bound
getLocalPort()
to.
isClosed() Checks if the socket is closed.
setSoTimeout(int timeout) Sets a timeout for the receive() method.
getSoTimeout() Gets the receive timeout value.
Event Handling in Java (AWT & Swing)
Event Handling in Java is a mechanism that allows your program to respond to user
interactions like:
Clicking a button
Typing in a text field
Moving the mouse
Selecting from a menu
It is a key concept in Graphical User Interface (GUI) programming, especially using AWT or
Swing.
Event Handling Process:
Java follows the event-delegation model:
1. Event Source
The GUI component (e.g., Button, TextField) that generates an event.
2. Event Object
An object that describes the event (e.g., ActionEvent, MouseEvent).
3. Event Listener
An interface with methods that receive and handle events.
4. Event Handler
The method that gets called when the event occurs.
Common Event Classes (from [Link]):
Class Description
ActionEvent Generated by buttons, menu items, etc.
MouseEvent Mouse clicks, presses, releases, movements
KeyEvent Keyboard actions
ItemEvent Item selection (checkbox, list, combo box)
WindowEvent Window actions (open, close, minimize)
Common Listener Interfaces:
Listener Interface Used For
ActionListener Buttons, menu items
MouseListener Mouse actions
KeyListener Keyboard input
ItemListener Checkboxes, lists
WindowListener Window events
Java Database Connectivity (JDBC)
Introduction
JDBC is an API that helps applications to communicate with databases, it allows Java programs
to connect to a database, run queries, retrieve, and manipulate data. Because of JDBC, Java
applications can easily work with different relational databases like MySQL, Oracle,
PostgreSQL, and more.
JDBC Architecture
Application: It can be a Java application or servlet that communicates with a data source.
The JDBC API: It allows Java programs to execute SQL queries and get results from the
database. Some key components of JDBC API include
o Interfaces like Driver, ResultSet, RowSet, PreparedStatement, and Connection
that helps managing different database tasks.
o Classes like DriverManager, Types, Blob, and Clob that helps managing database
connections.
DriverManager: It plays an important role in the JDBC architecture. It uses some database-
specific drivers to effectively connect enterprise applications to databases.
JDBC drivers: These drivers handle interactions between the application and the database.
The JDBC architecture consists of two-tier and three-tier processing models to access a database.
They are as described below:
1. Two-Tier Architecture
A Java Application communicates directly with the database using a JDBC driver. It sends
queries to the database and then the result is sent back to the application. For example, in a
client/server setup, the user's system acts as a client that communicates with a remote
database server.
Structure:
Client Application (Java) -> JDBC Driver -> Database
2. Three-Tier Architecture
In this, user queries are sent to a middle-tier services, which interacts with the database. The
database results are processed by the middle tier and then sent back to the user.
Structure:
Client Application -> Application Server -> JDBC Driver -> Database
JDBC Components
There are generally 4 main components of JDBC through which it can interact with a database.
They are as mentioned below:
1. JDBC API
It provides various methods and interfaces for easy communication with the database. It includes
two key packages
[Link]: This package, is the part of Java Standard Edition (Java SE) , which contains the
core interfaces and classes for accessing and processing data in relational databases. It also
provides essential functionalities like establishing connections, executing queries, and
handling result sets
[Link]: This package is the part of Java Enterprise Edition (Java EE) , which extends
the capabilities of [Link] by offering additional features like connection pooling, statement
pooling, and data source management.
It also provides a standard to connect a database to a client application.
2. JDBC Driver Manager
Driver manager is responsible for loading the correct database-specific driver to establish a
connection with the database. It manages the available drivers and ensures the right one is used
to process user requests and interact with the database.
3. JDBC Test Suite
It is used to test the operation(such as insertion, deletion, updating) being performed by JDBC
Drivers.
4. JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand. There are 4
types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver (partially java driver)
3. Type-3 driver or Network Protocol driver (fully java driver)
4. Type-4 driver or Thin driver (fully java driver) - It is a widely used driver. The older drivers
like (JDBC-ODBC) bridge driver have been deprecated and no longer supported in modern
versions of Java.
JDBC Classes and Interfaces
Class/Interfaces Description
Manages JDBC drivers and establishes database
DriverManager
connections.
Connection Represents a session with a specific database.
Statement Used to execute static SQL queries.
Precompiled SQL statement, used for dynamic queries
PreparedStatement
with parameters.
CallableStatement Used to execute stored procedures in the database.
Represents the result set of a query, allowing navigation
ResultSet
through the rows.
Handles SQL-related exceptions during database
SQLException
operations.
Steps to Connect to MySQL Database Using JDBC
Step 1: Load the JDBC Driver
[Link]("[Link]");
Step 2: Establish a Connection
Connection connection = [Link](
"jdbc:mysql://localhost:3306/your_database",
"your_username",
"your_password"
);
Step 3: Create a Statement
Statement statement = [Link]();
Step 4: Execute a Query
String query = "INSERT INTO students (id, name) VALUES (101, 'John Doe')";
int rowsAffected = [Link](query);
[Link]("Rows affected: " + rowsAffected);
Step 5: Close the Connection
[Link]();
Create a Simple JDBC Application
The below Java program demonstrates how to establish a MYSQL database connection using
JDBC and execute a query.
// Java program to implement a simple JDBC application
import [Link].*;
public class Geeks {
public static void main(String[] args)
{
// Database URL, username, and password
// Replace with your database name
String url
= "jdbc:mysql://localhost:3306/your_database";
// Replace with your MySQL username
String username = "your_username";
// Replace with your MySQL password
String password = "your_password";
// Updated query syntax for modern databases
String query
= "INSERT INTO students (id, name) VALUES (109, 'bhatt')";
// Establish JDBC Connection
try {
// Load Type-4 Driver
// MySQL Type-4 driver class
[Link]("[Link]");
// Establish connection
Connection c = [Link](
url, username, password);
// Create a statement
Statement st = [Link]();
// Execute the query
int count = [Link](query);
[Link](
"Number of rows affected by this query: "
+ count);
// Close the connection
[Link]();
[Link]();
[Link]("Connection closed.");
}
catch (ClassNotFoundException e) {
[Link]("JDBC Driver not found: "
+ [Link]());
}
catch (SQLException e) {
[Link]("SQL Error: "
+ [Link]());
}
}
}
Output: