0% found this document useful (0 votes)
12 views12 pages

Java Networking Basics and Sockets

This document covers Java programming concepts related to networking, event handling, and database connectivity (JDBC). It explains the use of sockets for network communication, the structure of HTTP requests, and the Java networking classes and interfaces. Additionally, it provides an overview of JDBC architecture, components, and a simple example of connecting to a MySQL database using JDBC.

Uploaded by

avnishkhare52
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views12 pages

Java Networking Basics and Sockets

This document covers Java programming concepts related to networking, event handling, and database connectivity (JDBC). It explains the use of sockets for network communication, the structure of HTTP requests, and the Java networking classes and interfaces. Additionally, it provides an overview of JDBC architecture, components, and a simple example of connecting to a MySQL database using JDBC.

Uploaded by

avnishkhare52
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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:

Common questions

Powered by AI

TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are both supported in Java's networking capabilities, but they serve different purposes. TCP is used for reliable, stream-based I/O across the network, suitable for applications where data integrity and delivery order are crucial. It employs congestion control, guarantees packet delivery, and maintains an established connection, making it ideal for general data transfer applications like HTTP . In contrast, UDP supports a faster, simpler point-to-point datagram-oriented model. It provides connectionless, non-guaranteed delivery, which is faster but less reliable, making it suitable for applications like live broadcasts or online gaming where speed is preferable over reliability .

Java handles client-side and server-side TCP connections using distinct classes tailored for each role. On the client side, the Socket class is used to create connections to server sockets, effectively initiating protocol exchanges. This class supports establishing a direct communication pathway, managing the client's end of the network socket. On the server side, the ServerSocket class functions as a listener, waiting for client connections. It handles the server endpoint and is designed to accept incoming connection requests, thus managing the server's aspect of the network communication. This distinction allows Java to efficiently manage bidirectional, persistent, point-to-point networking sessions .

Event handling in Java's GUI programming involves responding to user interactions such as button clicks, typing, or mouse movements. Java uses an event-delegation model, which involves several components: the event source (GUI component generating events), the event object (describing the event), the event listener (interface receiving and handling events), and the event handler (the method that executes when the event occurs). This modular approach allows for a clean separation of concerns, where components can independently manage how they respond to user interactions within an event-driven architecture .

The InetAddress class in Java is pivotal within the networking framework as it encapsulates both Internet Protocol (IP) addresses for host identification and provides methods to retrieve these addresses. This class supports both IPv4 and IPv6 formats, facilitating compatibility with a wide range of network setups. By abstracting IP details, InetAddress simplifies the process for applications to manage network host addresses, resolve hostnames, and establish connections efficiently, which is fundamental for network programming in Java .

The JDBC (Java Database Connectivity) API provides numerous benefits for Java programs interacting with databases. It allows Java applications to execute SQL queries, retrieve results, and handle data within relational databases, facilitating direct and efficient communication. JDBC supports both two-tier and three-tier architectures, offering flexibility in interacting directly with databases or through a middle tier. Additionally, JDBC extends its functionalities with classes and interfaces like DriverManager, Connection, and ResultSet, thus simplifying the management of database connections and manipulation of data. Notably, JDBC is crucial for cross-platform database operations as it supports various databases such as MySQL, Oracle, and PostgreSQL .

The java.net package in Java plays a crucial role in networking by providing the fundamental classes and interfaces needed to implement networking capabilities. Since its inception in version 1.0, it has supported TCP/IP networking both by extending the established stream I/O interface and adding the necessary features for building I/O objects across the network. The significance of the java.net package lies in how it effectively supports the TCP and UDP protocol families, allowing Java applications to create both reliable stream-based and fast, point-to-point datagram-oriented network models .

Establishing a MySQL database connection using Java JDBC involves several key components and steps. First, the JDBC driver must be loaded using Class.forName("com.mysql.cj.jdbc.Driver") to ensure the appropriate driver for MySQL is available. Next, a connection is established using `DriverManager.getConnection()` method with parameters specifying the database URL, username, and password. A `Statement` object is then created to execute SQL queries against the database. After the query is executed, operations such as updates or data retrieval can occur, and the connection is eventually closed to free the underlying resources. These components and steps provide a standardized approach to database interactions in Java applications .

Java's socket communication mechanism ensures reliable data transmission by using the Transmission Control Protocol (TCP). TCP manages to robustly string together packets, sorts, and retransmits them as necessary to provide reliable, stream-based connections between hosts. This end-to-end communication is facilitated by creating sockets that manage points within a network, making sure that the data transmission is conducted over a persistent, bidirectional connection. Furthermore, the ServerSocket class for servers and the Socket class for clients handle connection initiation and protocol exchange, thereby ensuring the reliability of communication .

Java's URL and URLConnection classes significantly enhance its networking capabilities by providing a robust means to handle URLs and establish connections over the Internet. The URL class encapsulates the attributes of a Uniform Resource Locator, allowing Java programs to represent and manipulate web addresses efficiently. URLConnection extends this functionality by establishing and managing communications linked to these URLs, supporting data retrieval and resource management over HTTP and other protocols. This allows Java applications to interact seamlessly with web resources, facilitating tasks such as downloading files or posting data to web servers, which are integral for modern web-based applications and services .

In Java, the DatagramPacket and DatagramSocket classes collectively support User Datagram Protocol (UDP) communication. DatagramPacket acts as a container for data in UDP communication, enabling the encapsulation of data and metadata, such as destination address and port. DatagramSocket, on the other hand, provides the mechanism to send and receive these packets. It handles the underlying network operations, allowing data to be transmitted without establishing a dedicated end-to-end connection, which is synonymous with UDP's connectionless nature and low-overhead, fast data transfer model. Together, they facilitate efficient, though non-guaranteed, communication suitable for applications needing sporadic or rapid data exchange .

You might also like