Nothing Special   »   [go: up one dir, main page]

Java NetworkingUnit3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Java Networking

Java Networking is a notion of connecting two or more computing devices


together to share the resources. Java programs 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.

 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.

Networking Terminologies

The widely used Java networking terminologies used are as follows:

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1. 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.

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

 TCP
 FTP
 Telnet
 SMTP
 POP etc.
3. Port Number

The port number is used to uniquely identify different applications. It acts as a


communication endpoint between applications. The port number is associated
with the IP address for communication between two applications.

4. 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.

5. 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.

6. 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.

Types of Socket

Java provides three different types of sockets:

Connection-oriented (TCP) socketsare implemented with the Socket class.

The Socket provides the programmer with two constructors.

1. Socket (String hostName, int port): Creates a socket connecting the local
host to the named host and port; can throw an UnknownHostException ad
host IOException.
2. Socket (InetAddress ip Address, int port): Creates a socket using a
preexisting InetAddress object and a port; can throw an IOException.

Some of the useful methods of socket class are:

i)public void connect(SocketAddress host,int timeout)throws IOException: This


method connects the socket to the specified host. This method is needed only
when we instantiate the Socket using the no-argument constructor.
ii) public InetAddress getInetAddress(): This method returns the address of the
other computer that this socket is connected to.

iii)public int getPort():Returns the port the socket is bound to on the remote
machine.

iv) public int getLocalPort(): Returns the port the socket is bound to on the
local machine.

v)public int getPort(): Returns the port the socket is bound to on the remote
machine.

v) public SocketAddress getRemoteSocketAddress(): Returns the address of the


remote socket.

vi) public InputStream getInputStream() throws IOException: Returns the input


stream of the socket. The input stream is connected to the output stream of the
remote socket.

vii) public OutputStream getOutputStream() throws IOException: Returns the


output stream of the socket. The output stream is connected to the input
stream of the remote socket.

viii) public void close() throws IOException: Closes the socket, which makes this
Socket object no longer capable of connecting again to any server.

2) Connectionless (UDP) sockets use the Datagramsocket class. Java supports


datagram communication through the following classes:

i) DatagramPacket: The class DatagramPacket contains several constructors


that can be used for creating packet object. One of them is:

DatagramPacket(byte[] buf, int length, InetAddress address, int port);

The key methods of DatagramPacket class are:

a) byte[] getData(): Returns the data buffer.

b) int getLength(): Returns the length of the data to be sent or the length of the
data received.

c) void setData(byte[] buf): Sets the data buffer for this packet.
d) void setLength(int length): Sets the length for this packet.

ii ) DatagramSocket: The class DatagramSocket supports various methods that


can be used for transmitting or receiving data a datagram over the network. The
key methods are:

a) void send(DatagramPacket p): Sends a datagram packet from this socket.

b) void receive(DatagramPacket p): Receives a datagram packet from the


socket.

Client Server

Server: Server is the one who provides requested services. A server is anything
that has some resource that can be shared. Servers are defined as fast-
processing devices that act as centralized repositories of network files, pro-
grams, databases, and policies. Following are the some example of server

1) Compute Servers: Provide computing power.

2) Print Servers: Manage a collection of printers.

3) Disk Servers: Provide networked disk space; and

4) Web Servers: Store web pages.

Client: Clients are the ones who request services. A client is simply any other en-
tity that wants to gain access to a particular server. The server is a permanently
available resource, while the client is free to "unplug" after it has been served.

Client-Server Communication

At a basic level, network-based systems consist of a server, client, and a media


for communication.
A computer running a program that makes a request for services is called client
machine.

A computer running a program that offers requested services from one or more
clients is called server machine. The media for communication can be wired or
wireless network.

Socket-Based Communication

Sockets provide an interface for programming networks at the transport layer.


Network communication using sockets is very much similar to performing file
I/O. In fact, socket handle is treated like file handle.

Socket Programming:

1. Java Socket programming is used for communication between the applica-


tions running on different JRE.
2. Java Socket programming can be connection-oriented or connection-less.
3. Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.

The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.
Creating a Server that sends Data

One can create a socket that can be used to connect a server and a client. Once
the socket is created, the server can send data to the client and the client can
receive it.

Steps to create a server that sends some strings (messages) to the client:

Step 1: At server side, create a server socket with some port number. This is
done using

ServerSocket class as:


ServerSocket ss = new ServerSocket (777);

Step 2: Now, one should make the server wait till a client accepts connection.
This is done using accept() method.

Socket s=ss.accерt():

Step 3: Attach output stream to the server socket using getOutputStream()


method. This method returns OutputStream object. This stream is used by the
socket to send data to client
OutputStream obj = s.getOutputStream();

Step 4: Take another stream like PrintStream to send data till the socket.

PrintStreant ps = new PrintStream();

Step 5: Finally, this PrintStream is used by the server to send data to the client.
To send data, one has print() or println() methods available in PrintStream.

Ps.println(str);

Step 6: Then close the connection. This can be done by closing all the streams
and socket at server side as:

ss.close(); //close serverSocket

s.close(); //close Socket

ps.close(); //close PrintStream

Code:
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server1 {


public static void main(String[] args) throws Exception {
ServerSocket ss=new ServerSocket(777);
Socket s=ss.accept();
System.out.println("Connection Established");
OutputStream obj= s.getOutputStream();
PrintStream ps=new PrintStream(obj);
String str="Hello Client";
ps.println(str);
ps.println("Bye");
ps.close();
ss.close();
s.close();
}
}
Creating a Client That Receives Data
One can write a program that receives all the strings sent from the server. Let us
follow these steps to this:
Step 1: We should create a socket at client side using Socket class as:
Sockets s = new Socket("IPAddress", port number);
Here the IP Address represents the IPAddress of the server machine where
Server1.java program is running. To know the IPAddress, we can use DOS
command, as C:\> ipconfig
This will display the IP Address of the machine where the command is applied.
Or, we can follow the commands:
Start settings → control panel→ Network connections→ right click on this to see
the local area connection' dialog box and there double click on Internet Protocol
(TCP/IP). It opens internet protocol properties dialog box where one can see the
IPAddress.
Step 2: One should add InputStream to the socket so that the socket will be able
to receive the data on the InputStream.
InputStream obj = s.getInputStream();
Step 3: To read the data from the socket into the client, we can take the help of
BufferedReader as:
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
Step 4: Now we can read data from the BufferedReader object, using read() or
readLine() methods. Read() method can read a single character at a time, where
as readLine() can read a string
Str= br.readLine();
Step 5: Close the connection by closing all the streams and sockets.
br.close(); //close the BufferedReader
s.close(); //close the Socket
Socket Program Using TCP/IP(Socket and Server Socket)
TCPserver.java
import java.net.*;
import java.io.*;
public class TCPserver{
public static void main(String args[]) throws IOException
{
ServerSocket s1 =null;
try
{

s1=new ServerSocket(98);
}
catch(IOException ul)
{
System.err.println("could not found port 98");
System.exit(1);
}

Socket c=null;
try
{
c=s1.accept();
System.out.println("connection from"+c);
}
catch(IOException e)
{
System.out.println("accept failed");
System.exit(1);
}
PrintWriter out=new PrintWriter(c.getOutputStream(),true);
BufferedReader in=new BufferedReader(new InputStreamReader
(c.getInputStream()));
String I;
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("I am ready type now");
while ((I=sin.readLine())!=null)
{
out.println(I);
}
out.close();
sin.close();
c.close();
s1.close();
}}

TCPclient.java
import java.net.*;

import java.io.*;

public class TCPclient


{
public static void main(String args[]) throws IOException
{
Socket s=null;

BufferedReader b= null;
try
{

s=new Socket(InetAddress.getLocalHost(),98);

//if you want to connect another machine in the network, specify the ip address

//s=new Socket(ip address of other machine,98);

b=new BufferedReader(new InputStreamReader(s.getInputStream()));


}
catch(UnknownHostException u)
{
System.err.println("I don't know host");
System.exit(0);
}
String inp;
while((inp=b.readLine())!= null)
{
System.out.println(inp); }
b.close();
s.close();
}}

Socket Program Using UDP/IP(DatagramSocket and DatagramPacket)


UDPserver.java
import java.net.*;

public class UDPserver


{
public static DatagramSocket ds;

public static byte buffer[]=new byte[1024];

public static void Myserver() throws Exception


{
int pos=0;

while(true)
{
int c=System.in.read();
switch(c)
{
case -1: System.out.println("Server quits");
return;

case '\r': break;

case'\n': ds.send(new DatagramPack-


et(buffer,pos,InetAddress.getLocalHost(),777));
pos=0;
break;
default:

buffer[pos++]=(byte)c;
}}}
public static void main(String args[]) throws Exception
{
System.out.println("Server ready...n please type here");
ds=new DatagramSocket(888);
Myserver();
}
}

UDPclient.java
import java.net.*;
public class UDPclient
{
public static DatagramSocket ds;
public static byte buffer[ ]=new byte[1024];

public static void Myclient() throws Exception


{
while(true)

DatagramPacket p=new DatagramPacket(buffer, buffer.length);


ds.receive(p);
System.out.println(new String(p.getData(),0,p.getLength()));
}
}

public static void main (String args[]) throws Exception


{
System.out.println("client - For quit press Ctrl+C");
ds=new DatagramSocket(777);
Myclient();
}}
JDBC
JDBC (Java Database Connectivity) is Java application programming interface
that allows the Java programmers to access database using Java code.
The Java application programming interface provides a mechanism for
dynamically loading the correct Java packages and drivers and registering them
with the JDBC Driver Manager that is used as a connection factory for creating
JDBC connections which supports creating and executing statements such as
SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the JDBC
architecture.
JDBC API
API stands for Application Programming Interface. It is essentially a set of
rules and protocols which transfers data between different software
applications and allow different software applications to communicate with
each other.
The JDBC API consists of a set of classes and interfaces written in the Java
programming language that provide a standard API for tool/database
developers and makes it possible to write industrial strength database
applications using an all-Java API.
The JDBC API makes it easy to send SQL statements to relational database
systems and supports all directories of SQL.
Components of JDBC
1. JDBC API
2. JDBC Driver Manager
3. JDBC Test Suite
4. JDBC-ODBC Bridge
1) JDBC API: The JDBC API provides programmatic access to relational data
from the Java programming language. The JDBC 4.0 API is divided into two
packages: java.sql and javax.sql. Both packages are included in the Java SE
and Java EE platforms.
2) JDBC DriverManager: The JDBC DriverManager class defines objects which
can connect Java applications to a JDBC driver. DriverManager has
traditionally been the backbone of the JDBC architecture.
3) JDBC Test Suite: The JDBC driver test suite helps to determine that JDBC
drivers will ran program. These tests are not comprehensive or exhaustive.
4) JDBC-ODBC Bridge: The Java Software Bridge provides JDBC access via
ODBC drivers. The ODBC drivers most appropriate on a corporate networks
where client installations are not a major problem or for application server
code written in Java in three-tier architecture.
The first two of these four JDBC components used to connect a database and
then build a java program that uses SQL commands to communicate with a test
Relational Database. The last two components are used in specialized
environments to test web applications or to communicate with ODBC-aware
DBMS.
Connectivity Model/JDBC Architecture
Java application calls the JDBC library. JDBC loads a driver which talks to the
database,The database engines can be changed without changing database
code. JDBC API supports both two-tier and three-tier processing models for
database access.
Types of JDBC Architecture(2-tier and 3-tier)
1. Two-tier model: A java application communicates directly to the data
source. The JDBC driver enables the communication between the applica-
tion and the data source. When a user sends a query to the data source, the
answers for those queries are sent back to the user in the form of results.
The data source can be located on a different machine on a network to
which a user is connected. This is known as a client/server configuration,
where the user’s machine acts as a client, and the machine has the data
source running acts as the server.

2. Three-tier model: In this, the user’s queries are sent to middle-tier services,
from which the commands are again sent to the data source. The results are
sent back to the middle tier, and from there to the user.
This type of model is found very useful by management information system
directors.
JDBC Driver

JDBC Driver is a software component that enables java application to interact


with the database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1. JDBC-ODBC bridge driver – Type 1 driver


Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls into the
ODBC function calls. Type-1 driver is also called Universal driver because it can
be used to connect to any of the databases.
Advantages
 This driver software is built-in with JDK so no need to install separately.
 It is a database independent driver.
Disadvantages
 As a common driver is used in order to interact with different databases, the
data transferred through this driver is not so secured.
 The ODBC bridge driver is needed to be installed in individual client ma-
chines.
 Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.

2. Native-API driver – Type 2 driver ( Partially Java driver)


The Native API driver uses the client -side libraries of the database. This driver
converts JDBC method calls into native calls of the database API. In order to
interact with different database, this driver needs their local API, that’s why
data transfer is much more secure as compared to type-1 driver. This driver is
not fully written in Java that is why it is also called Partially Java driver.

Advantage
 Native-API driver gives better performance than JDBC-ODBC bridge driver.
Disadvantages
 Driver needs to be installed separately in individual client machines
 The Vendor client library needs to be installed on client machine.
 Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
 It is a database dependent driver.
3. Network Protocol driver – Type 3 driver (fully Java driver)
The Network Protocol driver uses middleware (application server) that
converts JDBC calls directly or indirectly into the vendor-specific database
protocol. Here all the database connectivity drivers are present in a single
server, hence no need of individual client-side installation.

Advantages
 Type-3 drivers are fully written in Java, hence they are portable drivers.
 No client side library is required because of application server that can per-
form many tasks like auditing, load balancing, logging etc.
 Switch facility to switch over from one database to another database.
Disadvantages
 Network support is required on client machine.
 Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

4. Thin driver – Type 4 driver (fully Java driver)


Type-4 driver is also called native protocol driver. This driver interact directly
with database. It does not require any native database library, that is why it is
also known as Thin Driver.
Advantages
 Does not require any native library and Middleware server, so no client-side
or server-side installation.
 It is fully written in Java language, hence they are portable drivers.
Disadvantage
 If the database varies, then the driver will carry because it is database de-
pendent.
Which Driver to use When?
 If you are accessing one type of database, such as Oracle, Sybase, or IBM,
the preferred driver type is type-4.
 If your Java application is accessing multiple types of databases at the same
time, type 3 is the preferred driver.
 Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not
available yet for your database.
 The type 1 driver is not considered a deployment-level driver, and is typical-
ly used for development and testing purposes only.
ODBC

ODBC is Open Database Connectivity. It is a standard or open Application


Programming Interface (API) for accessing a database. It is product of
Microsoft which is developed by the SQL Access group in 1992. The goal of
ODBC is to make it possible to access any data from any application, regardless
of which DBMS is handling the data. ODBC manages this by inserting a middle
layer, called a database driver between an application and the DBMS.

The purpose of this layer is to translate the application's data queries into
commands that the DBMS understands. For this to work, both the application
and the DBMS must be ODBC Compliant, ie, the application must be capable of
issuing ODBC command and the DBMS must be capable of responding to them.

By using ODBC statements in a program, we can access files in a number of


different databases, including Access, dBase, DB2, Excel, and Text. It allows
programs to use SQL requests that ODBC will access databases without having
to know the proprietary interfaces to the databases, ODBC handles the SQL
request and converts it into a request the individual database system
understands.

ODBC Process

To use the ODBC, three components are needed:

1) ODBC client,

2) ODBC driver, and

3) DBMS server (e.g., Microsoft Access, SQL Server, Oracle, and FoxPro).

Firstly, the ODBC client will use a command (referred to as "ODBC") to interact
(requesting and/or sending data) with the DBMS server (back-end). However,
the DBMS server will not understand the command by the ODBC client yet, as
the command has yet to be processed through the ODBC driver (front-end). So
then, the ODBC driver will decode the command that can be processed by the
ODBC server and be sent there. The ODBC server will then respond back to the
ODBC driver which will translate the final output to the ODBC client.
ODBC Architecture

The ODBC architecture has four components:

1) Application: Performs processing and calls ODBC functions to submit SQL


statements and retrieve results.

2) Driver Manager: Loads and unloads drivers on behalf of an application. Pro-


cesses ODBC function calls or passes them to a driver.

3) Driver: Processes ODBC function calls, submits SQL requests to a specific data
source, and returns results to the application. If necessary, the driver modifies
an application's request so that the request conforms to syntax supported by
the associated DBMS.

4) Data Source: Consists of the data the user wants to access and its associated
operating system. DBMS, and network platform (if any) used to access the
DBMS.

i) Between the application, and

ii) The Driver Manager, and between the Driver Manager and each driver.

The interface between the Driver Manager and the drivers is sometimes re-
ferred to as Service Provider Interface, or SPI. For ODBC, the Application-
Programming Inter (API) and the Service Provider Interface (SPI) are the same.
That is, the Driver Manage and each driver have the same interface to the same
functions.

ODBC vs JDBC

S.No. ODBC JDBC


1. ODBC is for Microsoft. JDBC is for Java applications.
2. ODBC does not require man- JDBC drivers are written in Java and
ual installation of the ODBC JDBC code is automatically installable,
driver manager and driver on secure and portable on all platforms.
all client machines.
3. ODBC mixes simple and ad- JDBC is designed to keep things sim-
vanced features together and ple which allowing advanced capabili-
has complex options for sim- ties when required.
ple queries.
4. ODBC makes use of pointers JDBC does not makes use of pointers.
5. ODBC is language- JDBC is language-dependent.
independent.
Establishing Connection
For establishing the connection with database one need to follow the following
basics steps:
Step1: import java.sql package.
Step2: Loading a Database Driver
Syntax:
Class.forName(“path with driver name”);
Step3: Creating JDBC connection
Syntax:
Connection con=DriverManager.getConnection(URL, “administrator”,
“password”);
Step4: Creating a JDBC Statement Object
Statement stmt=connection.createStatement();
Step5: Executing the statement
The method to execute a simple query is Statement.executeQuery();
Step6: Closing the connection and statement.
Statement.close();
Connection.close();
Example Code:

Connection Pooling
A connection pool is a cache of database connections maintained in memory
so that the connections can be re-used when the database receives future
requests for data Connection pools are used to enhance the performance of
executing commands on a database.

In real word situation creating a database connection is a very expensive


operation for most database engines. If one have a server application, such as
a Java servlet or a middle-tier application server, that application is likely going
back and forth between the databases many times per minute. Suddenly, the
"open connection, talk to the database, close connection" model of JDBC
programming becomes a huge bottleneck.

The JDBC Optional Package provides a standardized solution to the problem


connection pooling. Connection pooling is a mechanism through which open
database connections are held in a cache for use and re-use by different parts
of an application.
A Java application talks only to a JDBC DataSource implementation. Internally,
the DataSource implementation talks to a ConnectionPoolDataSource, which
holds pooled database connections. When the application calls
getConnection() in the DataSource instance, it pulls a Connection out of the
connection pool.

The application works with its Connection just like any other Connection until
it is finished. It then closes the connection just as it normally would. Unknown
to the application, the physical link to the database is not being closed. Its
close() method returns it to the connection pool. If you try to use that
Connection again without getting it from the connection pool, it will throw an
exception.

You might also like