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

Unit3_Java

The document provides an overview of networking concepts in Java, including the use of sockets, InetAddress, URLs, TCP/IP client and server sockets, and datagrams. It also covers JDBC for database connectivity, detailing driver types and the steps for establishing a database connection. Code examples illustrate the practical implementation of these concepts in Java programming.

Uploaded by

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

Unit3_Java

The document provides an overview of networking concepts in Java, including the use of sockets, InetAddress, URLs, TCP/IP client and server sockets, and datagrams. It also covers JDBC for database connectivity, detailing driver types and the steps for establishing a database connection. Code examples illustrate the practical implementation of these concepts in Java programming.

Uploaded by

antonyraalph7
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Networking

• Networking is the concept of connecting two or more computing devices


to share resources.
• The application layer of a Java program communicates with the network.
The java.net package contains all of the Java networking classes and
interfaces.
• A socket identifies an endpoint in a network. It 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.
• Port number 21 is for FTP; 23 is for Telnet; 25 is for e-mail; 43 is for whois;
80 is for HTTP.
• 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.
Inet Address
• Java InetAddress class represents an IP address. It provides methods to get the IP
of any host name for example www.google.com, www.facebook.com, etc.
• An instance of InetAddress represents the IP address with its corresponding host
name.
• An IP address helps to identify a specific resource on the network using a
numerical representation.
Methods
getLocalHost(): This method retrieves the InetAddress object for the local machine.
getByName(String host): This method retrieves the InetAddress object for a remote
host given its hostname (e.g., "google.com").
getHostName(): This method returns the host name associated with the IP address.
getHostAddress(): This method returns the IP address associated with the
InetAddress object
import java.net.*;
class InetAddressDemo {
public static void main(String[] args) throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local Host Name: " + localHost.getHostName());
System.out.println("Local Host IP Address: " + localHost.getHostAddress());
InetAddress remoteHost = InetAddress.getByName("google.com");
System.out.println("Remote Host Name: " + remoteHost.getHostName());
System.out.println("Remote Host IP Address: " +
remoteHost.getHostAddress()); Local Host Name: prod-repl-java-79d66dffc5-qf94g
} Local Host IP Address: 10.236.0.20
Remote Host Name: google.com
}
Remote Host IP Address: 74.125.202.139
URL
• The Uniform Resource Locator (URL) provides a reasonably intelligible
form to uniquely identify or address information on the Internet.
• A URL specification is based on four components.
• The first is the protocol to use, separated from the rest of the locator by
a colon (:)
• The second is the host name or IP address of the host to use; this is
delimited on the left by double slashes (//) and on the right by a slash (/)
• The third is a the port number, is an optional parameter, delimited on
the left from the host name by a colon (:) and on the right by a slash (/)
• The fourth part is the actual file path.
Examples: https://www.HerbSchildt.com/index.htm.
https://www.shopify.com:443/products?id=123
import java.net.*;
class URLDemo{
public static void main(String[] args) throws MalformedURLException {
URL hp = new URL("https://www.shopify.com:443/products?id=123");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
}
} Protocol: https
Port: 443
Host: www.shopify.com
File: /products?id=123
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.
• 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.
• The creation of a Socket object implicitly establishes a connection
between the client and server.
Example : Lab exercise 5
TCP/IP Server Sockets
• The ServerSocket class is used to create servers that listen for either local or
remote client programs to connect to them on published ports.
• When you create a ServerSocket, it will register itself with the system as having
an interest in client connections.
Constructors

Example
1. ServerSocket serverSocket = new ServerSocket(port);
2. ServerSocket serverSocket = new ServerSocket(port, maxQueue);
import java.io.*;
import java.net.*;
public class ServerSocketExample {
public static void main(String[] args) throws IOException{
int port = 8080; // Specify the port number
int maxQueue = 100; // Specify the maximum queue length
// Creating the ServerSocket with the specified port
ServerSocket serverSocket = new ServerSocket(port, maxQueue);
System.out.println("Server started on port " + port + " with
maxQueue = " + maxQueue);
}
}
Server started on port 8080 with maxQueue = 100
Datagrams
• A datagram is an independent, self-contained message sent over the network.
• Datagrams are bundles of information passed between machines.
• 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.
• The send( ) method sends a packet to the port specified by packet.
• The receive( ) method waits for a packet to be received and returns the result.
Constructors
DatagramSocket( ) throws SocketException
DatagramSocket(int port) throws SocketException
DatagramPacket(byte data [ ], int size)
DatagramPacket(byte data [ ], int offset, int size)
DatagramPacket(byte data [ ], int size, InetAddress ipAddress, int port)
Send and receive UDP packets using
DatagramSocket and DatagramPacket
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String message = "Hello Server!";
byte[] sendData = message.getBytes();
InetAddress serverAddress = InetAddress.getByName("localhost");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
serverAddress, 9876);
socket.send(sendPacket);
System.out.println("Sent: " + message);
socket.close();
} Sent: Hello Server!
}
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws SocketException {
DatagramSocket socket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("Received: " + message);
}
} Received: Hello from server!
}
JDBC
• 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.
JDBC Driver Types
• The JDBC driver specification classifies JDBC drivers into four groups. Each group is
referred to as a JDBC driver type and addresses a specific need for communicating
with various DBMSs.
Type 1 Driver (JDBC-ODBC Bridge Driver):
• This driver translates JDBC calls into ODBC (Open Database Connectivity) calls.
• It relies on an ODBC driver to connect to the database, which means it requires the
ODBC driver to be installed on the client machine.
• It’s platform-dependent, not ideal for large-scale applications, and has been
deprecated by many vendors.
Type 2 Driver (Native-API Driver):
• This driver converts JDBC calls directly into database-specific calls, using the
database’s native API.
• It is faster than the Type 1 driver but still depends on the client having database-
specific software (like Oracle client libraries) installed.
• This makes it platform-dependent, and while faster than Type 1, it can still cause
issues in large distributed environments.
Type 3 Driver (Network Protocol Driver):
• This driver communicates with the database through a middleware server that
handles communication with the database.
• It doesn’t require any database-specific client software, making it more portable than
Types 1 and 2.
• The server-side middleware manages the communication, so it is often used for web-
based applications.

Type 4 Driver (Thin Driver or Direct-to-Database Driver):


• This driver is the most efficient as it communicates directly with the database using the
database's native protocol, without any need for middleware or client-side
installations.
• It is purely written in Java and platform-independent, which makes it the most
commonly used driver today.
• Type 4 drivers are ideal for internet-based applications and are typically the default
choice for many modern applications.
Database Connection - Steps
1. Load the JDBC Driver
• The first step is to load the appropriate JDBC driver for the database you are using.
• The JDBC driver acts as a bridge between Java and the database, translating Java calls into the
appropriate database-specific calls.
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // MySQL driver example
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found.");
e.printStackTrace();
}
• For a MySQL database, the driver com.mysql.cj.jdbc.Driver is loaded.
• The driver class will vary depending on the database (e.g., oracle.jdbc.OracleDriver for Oracle,
org.postgresql.Driver for PostgreSQL).
2. Establish the Database Connection
• The next step is to establish a connection to the database using the
DriverManager.getConnection() method.
• This method takes the database URL, username, and password as
parameters.
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
String user = "root"; // Database username
String password = "password"; // Database password
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connection successful!");
} catch (SQLException e) {
System.out.println("Connection failed.");
e.printStackTrace();
}
3. Create a Statement Object - Used for executing simple SQL queries.
• After establishing the connection, you create a Statement object to execute SQL
queries or updates.
Statement stmt = conn.createStatement();
4. Execute SQL Queries or Updates
• After creating the Statement object, you can execute SQL queries (for retrieving
data) or updates (for modifying data).
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
while (rs.next()) {
System.out.println(rs.getString("name") + ", " + rs.getInt("age"));
}
• The executeQuery() method runs a SELECT query and returns a ResultSet object.
• ResultSet is used to retrieve the data from the result set returned by the query.
5. Close the Connection
• After all database operations are completed, it's essential to close the
database connection, as well as any Statement or ResultSet objects.
try {
if (stmt != null) stmt.close();
if (rs != null) rs.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace(); // t
}

You might also like