Module 4 Java
Module 4 Java
A database system consists of a database, the software that stores and manages data in the
database, and the application programs that present data and enable the user to interact with the
database system. Almost all the current applications that we use require a database management
system at backend inorder to handle the data associated with the application. When you purchase a
database system, such as MySQL, Oracle, IBM, Microsoft, or Sybase, from a software vendor, you
actually purchase the software comprising a database management system (DBMS).All Data Base
systems make use of the universal query language SQL(Standard Query language) for manipulating
and accessing data associated with them.
Different database systems have surprisingly little in common: just a similar purpose and
a mostly compatible query language. Beyond that, every database has its own API that you must learn
to write programs that interact with the database. So writing code capable of interfacing with
databases from more than one vendor was a great challenge.
Since nearly all relational database management systems (RDBMSs) support SQL, and
because Java itself runs on most platforms, JDBC makes it possible to write a single database
application that can run on different platforms and interact with different DBMSs.. Only thing we
need to do is to make use of the driver which is specific to the database used at the backend.
In short JDBC helps the programmers to write java applications that manage these three
programming activities:
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 and it is capable of supporting multiple concurrent drivers connected
to multiple heterogeneous databases. JDBC drivers are normally provided by specific data base
vendors and they serve as the interface to facilitate communications between JDBC and a proprietary
database
DriverManager is the very important part of the JDBC architecture whose main purpose
is to provide a means of managing the different types of JDBC database driver. On running an
application, it is the DriverManager's responsibility to load all the drivers found in the system
properly. It then matches connection requests from the java application with the proper database
driver. When opening a new connection to a database it is the Driver Manager's duty to choose the
most appropriate driver from the previously loaded drivers. Internally, JDBC DriverManager is a
class in JDBC API and objects of this class can connect Java applications to a JDBC driver
JDBC Drivers are written by vendors and must support the basic features of the JDBC
specification ie, JDBC drivers should implement interfaces and classes defined by the JDBC API for a
particular DBMS vendor. It serves as the interface to facilitate communications between JDBC and a
proprietary database. It processes JDBC methods invocations, sends SQL statements to a specific data
source, and returns results back to the application. It translates and/or optimizes requests so the request
conforms to the syntax supported by the specific DBMS providing database independence.. If the back-
end database changes, only JDBC driver need to be replaced.
Type 1 drivers use another technology such as Open Database Connectivity (ODBC) to
communicate with a database. ODBC is a proprietary format developed by Microsoft that enables
communication between databases clients running on Windows and DBMS available on the market.
Since there are different types of databases and each of them has its own way of dealing with SQL
queries and to return the results, ODBC provides identical results regardless of the type of database,
without the need for you to configure the program that sends the request. This is an advantage because
ODBC drivers exist for many Relational Database Management System (RDBMS) platforms This
driver is included in the Java 2 SDK within the sun.jdbc.odbc package and it translates JDBC method
calls into ODBC function calls and sends them to the ODBC driver. The Bridge implements JDBC for
any database for which an ODBC driver is available.
In order to use Type 1 drivers ODBC must be installed on the computer having the driver
and the database which is being connected to must support an ODBC driver. This is platform-
dependent as it makes use of ODBC which in turn depends on native libraries of the operating system.
Applications that make use of this driver cause performance overhead since the calls have to go
through the JDBC overhead bridge to the ODBC driver, then to the native db connectivity interface.
Type 1 drivers are not suitable for developing web applications as they need software to be installed on
client machine
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when no other
alternative is available.
Type 2 drivers use the Java Native Interface (JNI) to make calls to a local
database library API. This driver converts the JDBC calls into a database specific call for databases
such as SQL, ORACLE etc i.e. this driver is specific to a particular database. This driver
communicates directly with the database server and requires some native code to connect to the
database. These drivers typically provided by the database vendors and used in the same manner as
the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine. If we
change the Database we have to change the native API driver as it is specific to a database. Since
Native API must be installed in the Client System type 2 drivers cannot be used for the Internet. The
distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance
than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type1
The JDBC type 3 driver, also known as the network-protocol driver is a database driver
implementation which makes use of a middle-tier between the calling program and the database. The
middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific
database protocol. Type 3 database requests are passed through the network to the middle-tier server
and the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers to translate the request to
the database. Since the communication between client and the middleware server is database
independent, there is no need for the vendor db library on the client machine.
This driver is very flexible as it allows access to multiple databases using one driver .The
number of data bases that can be accessed depends on the number of databases the middleware has
been configured to support. Type 3 driver is suitable for developing web applications since there is no
client side software needed. One of the disadvantages of this driver is that database-specific coding
should be done in the middle tier.
Type 4 drivers are pure Java drivers that implement a proprietary database protocol
to communicate directly with the database. Like Type 3 drivers, they do not require native database
libraries and can be deployed over the Internet without client installation. One drawback to Type 4
drivers is that they are database specific. Unlike Type 3 drivers, if your back-end database changes,
you may save to purchase and deploy a new Type 4 driver (some Type 4 drivers are available free of
charge from the database manufacturer). However, because Type 4 drivers communicate directly with
the database engine rather than through middleware or a native library, they are usually the fastest
JDBC drivers available. This driver directly converts the java statements to SQL statements. The
major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve
platform independence and eliminate deployment administration issues. This is the highest
performance driver available for the database and is usually provided by the vendor itself. The only
disadvantage is that we need to download a new driver for each database engine.
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is
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 typically used for development
and testing purposes only.
The java.sql package contains the entire set of interfaces and classes defined by JDBC
API that sends SQL (Structured Query Language) statements to relational databases and retrieves the
results of executing those SQL statements.
The cornerstone of the JDBC package is the DriverManager class. This class keeps track
of all the different available database drivers. The DriverManager manages loading and unloading
drivers. The DriverManager maintains a Vector that holds information about all the drivers that it
knows about. The elements in the Vector contain information about the driver such as the class name
of the Driver object, a copy of the actual Driver object, and the Driver security context. The
DriverManager, while not a static class, maintains all static instance variables with static access
methods for registering and unregistering drivers.
METHODS:
public static Driver getDriver(String URL) throws SQLException- Finds a driver that
understands the JDBC URL from the registered driver list
The Date class is used to represent dates in the SQL format YYYY-MM-DD. It contains methods to
perform conversions of java.util.Date and the SQL DATE type
METHODS
public static Date valueOf (String str)-Converts a String str to an sql.Date object
The Time class is used to represent times in the SQL format HH:MM:SS. It contains methods to
perform SQL TIME type and Java Time object conversions.
METHODS:
public String toString()-Returns a String with the Time formatted this way: HH:MM:SS
public static Time valueOf(String numStr)-Returns a Numeric object from the String numStr
parameter that is in the format: HH:MM:SS
4.1.3.4 TIMESTAMP
The Timestamp class is used to represent a combination of date and time values in the ANSI SQL
format YYYY-MMDD HH:MM:SS.F
METHODS:
public boolean equals(Timestamp tstamp) Compares the Timestamp object with the Timestamp
parameter tstamp; returns true if they match
The Driver is the software wedge that communicates with the platform-dependent
database, either directly or using another piece of software. How it communicates really depends on
the database, the platform, and the implementation. So All JDBC Drivers must implement the Driver
interface and each driver should supply a class that implements the Driver interface.
jdbc:<sub-protocol>:<sub-name> , where
sub-protocol is the name of the driver set that defines a particular database connectivity method. This
can be represented by several drivers.
sub-name is the additional information necessary to complete the URL. This information is different
depending on the sub-protocol.
Eg:String url = “jdbc:odbc:mysource”;
Using the getConnection() method, the DriverManager asks each driver that has
registered with it whether the database connection URL is valid. If one driver responds positively, the
DriverManager assumes a match. If no driver responds positively, an SQLException is thrown. The
DriverManager returns the error "no suitable driver," which means that of all the drivers that the
DriverManager knows about, not one of them could figure out the URL you passed to it.
The following methods can be used to easily navigate the results a query returns:
boolean getMoreResults()
This moves to the next result set in the Statement. This, like the execute() method, returns true if the
next result is a result set or false if it is an integer. If you have already retrieved a ResultSet from the
Statement, this method will close it before returning.
ResultSet getResultSet()
This method returns to you a result set in a ResultSet object. This result set is the current result set.
int getUpdateCount()
This method returns to you the integer result that an execute() method returned.
The SQL statements that read data from a database query return the data in a result set.
The SELECT statement is the standard way to select rows from a database and view them in a result
set. The java.sql.ResultSet interface represents the result set of a database query A ResultSet object
maintains a cursor that points to the current row in the result set. When a ResultSet object is created,
its position is always before the first row of data contained within the ResultSet. The methods of the
ResultSet interface can be broken down into three categories:
NAVIGATIONAL METHODS:
A ResultSet provides access to a table of data generated by executing a Statement. The table rows
are retrieved in sequence and it maintains a cursor pointing to its current row of data. There are
several methods in the ResultSet interface that involve moving the cursor:
When you've retrieved all the data you can from a column, it is time to move on to the next row.
Moving to the next row is done with the next() method. This method returns a boolean value
indicating the status of the row. Internally, it moves the ResultSet's cursor to the next row, thereby
giving access to the data stored in the columns of that row.
public boolean next()-Moves the cursor to the next row. This method returns false if there are no
more rows in the result set. The first call to next() makes the first row available to your program
public int getRow()-Returns the row number that the cursor is pointing to
public boolean absolute(int row) -Moves the cursor to the specified row.
public boolean relative(int row)-Moves the cursor the given number of rows forward or backwards
from where it currently is pointing.
The ResultSet interface contains dozens of methods for getting the data of the current
row. There is a get method for each of the possible data types, and each get method has two versions:
one that takes in a column name, and one that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one of the
getInt() methods of ResultSet:
public int getInt(String columnName)-Returns the int in the current row in the column named
columnName.
public int getInt(int columnIndex) -Returns the int in the current row in the specified column index.
The column index starts at 1, meaning the first column of a row is 1, the second column of a row is 2,
and so on.
There are get methods in the ResultSet interface for each of the eight Java primitive types, as well as
common types such as java.lang.String and java.lang.Object. There are also methods for getting SQL
data types java.sql.Date, java.sql.Time, java.sql.TimeStamp.
The ResultSet interface contains a collection of update methods for updating the data of a
result set. As with the get methods, there are two update methods for each data type: one that uses the
column name and one that uses the column index. For example, to update a String column of the
current row of a result set, you would use one of the following updateString() methods:
public void updateString(int columnIndex, String s) -Changes the String in the specified column
to the value of s.
public void updateString(String columnName, String s)-Similar to the previous method, except
that the column is specified by its name instead of its index.
There are update methods for the eight primitive data types, as well as String and the SQL data types
in the java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet object, but
not in the underlying database. To update your changes to the row in the database, you need to invoke
the following method:
public void updateRow()-Updates the current row by updating the corresponding row in the
database.
For example, the following prepared statement inserts a new row in a table called Employees:
This prepared statement contains four parameters. When the Prepared- Statement object is created
using the Connection object, this statement is sent to the database and precompiled, allowing the
database to execute the statement at a faster rate.
Connection Interface, contains different methods for creating a PreparedStatement. The method
public PreparedStatement prepareStatement(String sql) creates a prepared SQL statement. The
SQL is sent to the database for precompilation.
Each question mark in a prepared statement denotes a parameter. The order in which the parameters
appear determines their index, with the first parameter being index 1, the second parameter index 2,
and so on. This is important when you go to set the values using the various set methods in the
PreparedStatement interface.
Use the appropriate set methods of the PreparedStatement interface to set each of the
parameters of the prepared statement.
Before a prepared statement can be executed, each of its parameters must be assigned a value. The
PreparedStatement interface contains a set method for each of the possible data types of a
parameter. Each set method takes in an index to denote which parameter to set. For example, if the
data type of the parameter is a double, then you use the method.
Eg: The following statements prepare a statement and assign each of its four parameters a value using
the appropriate set method:
PreparedStatement insert =
connection.prepareStatement(“INSERT INTO Employees VALUES (?, ?, ?, ?)”);
insert.setDouble(2, 2.50);
insert.setInt(1, 103);
insert.setString(3, “George”);
insert.setString(4, “Washington”);
Notice that the order in which you set the parameters does not matter, as long as you set a
value for each parameter of the prepared statement.
Invoke one of the execute() methods of the PreparedStatement interface to execute the
statement.
After the values of all the parameters are set, the prepared statement is executed using one of the
following methods in the PreparedStatement interface:
public ResultSet executeQuery()-Use this method if the SQL statement returns a result set, like a
SELECT statement.
public int executeUpdate()-Use this method for statements like INSERT, UPDATE, or DELETE.
The return value is the number of rows affected.
public boolean execute()-This method executes any type of SQL statement. Use the getResultSet()
method to obtain the result set if one is created
This is the primary interface to access stored procedures on a database. A stored procedure
allows you to repeat a sequence of tasks repeatedly in an efficient manner, much like writing a
method in Java. Use one of the prepareCall() methods of the Connection interface to create a
CallableStatement object:
Following are the different steps involved in using JDBC to access a database
1. importing java.sql
java.sql package contains all the classes and interfaces we need to create and manage a
data base connection. Inorder to make use of these classes and interfaces we need to import them in
our program
In this step of the jdbc connection process, we load the driver class by calling
Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an
instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the
Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used. The
return type of the Class.forName (String ClassName) method is “Class”. Class is a class in java.lang
package.
try
{
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
}
catch(Exception x)
{
System.out.println( “Unable to load the driver class!” );
}
3. Connecting to DBMS
The JDBC DriverManager class defines objects which can connect Java applications to a
JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class
manages the JDBC drivers that are installed on the system. Its getConnection() method is used to
establish a connection to a database. It uses a username, password, and a jdbc url(that represents the
name of the data source) to establish a connection to the database and returns a connection object. A
jdbc Connection represents a session/connection with a specific database. Within the context of a
Connection, SQL, PL/SQL statements are executed and results are returned. An application can have
one or more connections with a single database, or it can have many connections with different
databases. A Connection object provides metadata i.e. information about the database, tables, and
fields. It also contains methods to deal with transactions.
All JDBC URLs start with jdbc. The subprotocol is actually determined by the driver you
are using. The subname can contain additional information used by the satisfying subprotocol
(i.e.driver), such as the location of the data source, as well as a port number
EXAMPLE:
This method returns a Connection interface that is used throughout the process to reference the
database.
Once a connection is obtained we can interact with the database. Connection interface defines
methods for interacting with the database via the established connection. To execute SQL statements,
you need to instantiate a Statement object from your connection object by using the createStatement()
method.
A statement object is used to send and execute SQL statements to a database. There are three
kinds of Statements
EXAMPLE:
EXAMPLE:
Statement interface defines methods that are used to interact with database via the
execution of SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is
executeQuery . For statements that create or modify tables, the method to use is executeUpdate. Note:
Statements that create a table, alter a table, or drop a table are all examples of DDL statements and
are executed with the method executeUpdate(). execute() executes an SQL statement that is written
as String object.
EXAMPLE:
A result set provides access to a table of data generated by executing a Statement. The
table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of
data. The next() method is used to successively step through the rows of the tabular results. Within a
row,ResultSet provides various getXxx methods that take a column index or column name as an
argument and return the result as a variety of different Java types and the the first column in a
ResultSet row has index 1.
EXAMPLE:
while(resultSet.next())
{
System.out.println(results.getString(1) + " " + results.getString(2) + " ” +results.getString(3));
}
7. Close connection
We should postpone this step if we expect to perform additional database operations, since the
overhead of opening a connection is usually large. In fact, reusing existing connections is such an
important optimization.
import java.sql.*
{
String userName = "testuser";
String password = "testpass";
String url = "jdbc:mysql://localhost/test";
try
{
Class.forName ("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (url, userName, password);
//Create a Statement class to execute the SQL statement
Statement stmt = con.createStatement();
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " +
rs.getString("releasedate");
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// Close the connection
con.close();
}
}
4.2 NETWORKING-INTRODUCTION
to translate this domain name into a numeric IP address and then sends the request using the IP
address.
We need to specify certain set of rules that needs to be followed when a system
communicates with another system. A protocol is a precise set of rules defining how computers
communicate: the format of addresses, how data is split into packets, etc. There are many different
protocols defining different aspects of network communication. For example HTTP is used to transfer
HTML documents on the Web and FTP allows you to transfer binary files over the Internet. Both
protocols have their own set of rules and standards on how data is transferred.
Each computer on the internet can provide a variety of services and the type of service must
be known before information can be transferred. Each computer with an IP address has several
thousand logical ports. These are purely abstractions in the computer's memory and do not represent
anything physical like a serial or parallel port. Each port is identified by a number from 1 to 65,535.
and each port can be allocated to a particular service.
For example, the HTTP service, which is used by the Web, generally runs on port 80: we
say that a web server listens on port 80 for incoming connections. SMTP or email servers run on port
25. When data is sent to a web server on a particular machine at a particular IP address, it is also sent
to a particular port (usually port 80) on that machine. The receiver checks each packet it sees for the
port and sends the data to any programs that are listening to the specified port. Port numbers from 1
to 1023 are reserved for well-known services such as finger, FTP, HTTP, and email.
Data transmitted over the internet follows a specific protocol and is accompanied by
addressing information that identifies the computer (IP address) and the port for which it is destined.
The receiver checks each packet it sees for the port and sends the data to any programs that are
listening to the specified port.
The socket is the software abstraction used to represent the "terminals" of a connection
between two machines. Network programming usually involves a server and one or more clients. The
client sends requests for information/services own by the Server. Once the connection is established
between Client and Server, they can start sending / receiving information. Socket acts as an interface
through which sever and client can send / receive information and it is identified by using the port
number and IP address In a nutshell, a socket on one computer that talks to a socket on another
computer creates a communication channel. A programmer can use that channel to send data between
the two machines.
Java treats socket communications much as it treats I/O operations; thus programs can read from
or write to sockets as easily as they can read from or write to files.
The socket associates the server program with a specific hardware port on the machine where it
runs so any client program anywhere in the network with a socket associated with that same port can
communicate with the server program. The server waits and listens to the socket for a client to make a
connection request
The server accepts the connection request from client which contains the name of
the server and port number. Upon acceptance, the server creates a new socket bound to a different
port and this new socket is dedicated for serving the client that had sent request. The original socket
can continue to listen for further connection requests
The java.net package contains a collection of classes and interfaces that provide
functionalities for writing programs that execute across multiple devices (computers), in which the
devices are all connected to each other using a network. Some of the important classes available in
java.net Package are:
InetAddress
ServerSocket
Socket
DatagramPacket
DatagramSocket
URL
When you are establishing a connection across the Internet, addresses are fundamental. The
java.net.InetAddress class is Java's encapsulation of an IP address. It is used by most of the other
networking classes, including Socket, ServerSocket, URL, DatagramSocket, DatagramPacket. This
class represents an Internet address as two fields: hostName (a String) and address (an int).
There are no public constructors in the InetAddress class. However, InetAddress has three static
methods that return suitably initialized InetAddress objects, given a little information.
EXAMPLE:
import java.net.*;
class InetAddressTest
{
public static void main(String args[])throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.yahoo.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.google.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
OUTPUT
COMPAQ-PC/192.168.2.2
www.yahoo.com/106.10.170.118
www.google.com/74.125.235.50
www.google.com/74.125.235.51
www.google.com/74.125.235.52
www.google.com/74.125.235.48
www.google.com/74.125.235.49
The InetAddress class contains getter methods that return the hostname and the IP address as a string
String getHostAddress(): Returns a string that represents the host address associated with the
InetAddress object.
String getHostName():Returns a string that represents the host name associated with the InetAddress
object.
The java.net package provides support for the two common network protocols:
TCP: TCP, Transmission Control Protocol is a connection oriented protocol which allows for
reliable communication between two applications. It guarantees that data sent from one end of the
connection actually gets to the other end and in the same order it was sent. Otherwise, an error is
reported
UDP: UDP, User Datagram Protocol, is a connection-less protocol that allows for packets of data to
be transmitted between applications. The destination port and IP addresses are written down in a
datagram and the datagram is sent to the destination. UDP does not guarantee that packets will be
received in the order they were sent
reliable, two-way communication stream that allows data to be transmitted in either direction. Using
TCP provides a Stream-based communication for data transmission and it can detect lost
transmissions and resubmit them. The two computers can communicate until the connection is closed
or lost. The java.net.ServerSocket and java.net.Socket classes are the only two classes you will
probably ever need to create a TCP/IP connection between two computers for you. The
java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
The actual reading and writing of data over the socket is accomplished via the
familiar stream classes. After the connections are established, communication can occur using I/O
streams. Each socket has both an OutputStream and an InputStream. The client’s OutputStream
is connected to the server’s InputStream, and the client’s InputStream is connected to the server’s
OutputStream. TCP is a two way communication protocol, so data can be sent across both streams
at the same time.
When the Socket constructor returns, it does not simply instantiate a Socket object. Within the
constructor, it actually attempts to connect to the specified server and port.
METHODS
InetAddress getInetAddress()-Given a Socket object, this method tells which remote host the
Socket is connected to or, if the connection is now closed, which host the Socket was connected to
when it was connected
int getPort() - tells you which port the Socket is (or was or will be) connected to on the remote host.
InputStream getInputStream()-returns an input stream that can read data from the socket into a
program. You can chain this InputStream to a filter stream or reader that offers more functionality
DataInputStream or InputStreamReader before reading input. It's also extremely helpful to buffer the
input by chaining it to a BufferedInputStream or a BufferedReader for performance reasons.
public void close()- Closes the socket, which makes this Socket object no longer capable of
connecting again to any server.
3. Once the connection is established, the local and remote hosts get input and output streams from
the socket and use those streams to send data to each other.
4. When the transmission of data is complete, one or both sides close the connection.
EXAMPLE:
To establish a server, you need to create a server socket and attach it to a port, which is where
the server listens for connections. The java.net.ServerSocket class is used by server applications to
obtain a port and listen for client requests. It has constructors that create new ServerSocket objects,
methods that listen for connections on a specified port, and methods that return a Socket object when
a connection is made so that you can send and receive data.
A server socket waits for requests from client to come in over the network. When a client
Socket on a remote host attempts to connect to that port, the server wakes up, negotiates the
connection between the client and the server, and opens a regular Socket between the two hosts. Once
the server socket has set up the connection, the server uses a regular Socket object to send data to the
client. Following are the most commonly used constructors of this class.
public ServerSocket (int port)- creates a server socket on the port specified by the argument. The
constructor throws an IOException (specifically, a BindException) if the socket cannot be created
and bound to the requested port.
public ServerSocket(int port, int queueLength)- This constructor creates a ServerSocket on the
specified port with a queue length of your choosing. If the machine has multiple network interfaces or
IP addresses, then it listens on this port on all those interfaces and IP addresses. The queueLength
argument sets the length of the queue for incoming connection requests—that is, how many incoming
connections can be stored at one time before the host starts refuse connections
public ServerSocket(int port, int qLength, InetAddress address)- The InetAddress parameter
specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple
IP addresses, allowing the server to specify which of its IP addresses to accept client requests on
METHODS
public int getLocalPort()-Returns the port that the server socket is listening on.
public Socket accept() - returns a Socket object representing the connection between the remote
client and the local server. It stops the flow of execution and waits until a client connects
We use the streams returned by this Socket's getInputStream() and getOutputStream() methods to
communicate with the client.
2. The server invokes the accept() method of the ServerSocket class. accept() blocks until a client
attempts to make a connection, at which point accept() returns a Socket object connecting the
client and the server.
4. The server and the client interact according to an agreed-upon protocol until it is time to close the
connection.
6. The server returns to step 2 and waits for the next connection.
EXAMPLE:
The InputStream and OutputStream attributes of a Socket are the ways the two
computers communicate with each other. For example, if the server wants to send data to the client,
the server needs to write to the OutputStream of its socket, which is then read by the InputStream of
the client’s socket. Similarly, data can be sent from the client to the server using the client’s
OutputStream and the server’s InputStream.
String sent1;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
User Datagram Protocol (UDP) provides a protocol for sending packets of data
called datagrams between applications. If TCP is similar to placing a telephone call, UDP can be
compared to mailing someone a letter. The datagram packet is like a letter, where a client sends a
datagram to a server without actually connecting to the server. This makes UDP an unreliable
communication protocol when compared to TCP, where the client and server are directly connected.
If I mail you two letters on the same day, they might be delivered on the same day,
but this is hardly guaranteed. In fact, there is no guarantee that both letters will even get delivered at
all. It’s possible that one will be delivered the next day, whereas the other doesn’t arrive for two
weeks. The same is true for datagram packets. UDP does not guarantee that packets will be received
in the order they were sent or that they will even be delivered at all. If this type of unreliability is
unacceptable for the program you are developing, you should use TCP instead. However, if you’re
developing a network application in which reliable communication is not essential to the application,
UDP is probably a better option because it does not carry the overhead of TCP.
This division of labour contrasts with the Socket and ServerSocket classes used by
TCP.UDP doesn't have any notion of a server socket. You use the same kind of socket to send data
and to receive data. Second, TCP sockets allow you to treat a network connection as a stream: you
send and receive with input and output streams that you get from the socket. UDP doesn't allow this;
you always work with individual datagram packets. All the data you stuff into a single datagram is
sent as a single packet and is either received or lost as a group. One packet is not necessarily related
to the next. Given two packets, there is no way to determine which packet was sent first and which
was sent second. Instead of the orderly queue of data that's necessary for a stream, datagrams try to
crowd into the recipient as quickly as possible, like a crowd of people pushing their way onto a bus.
A third difference, which is really a consequence of the first two, is that a single DatagramSocket can
send data to and receive data from many independent hosts. The socket isn't dedicated to a single
connection, as it is in TCP. In fact, UDP doesn't have any concept of a connection between two hosts;
it only knows about individual datagrams. Figuring out who sent what data is the application's
responsibility.
The java.net.DatagramSocket class is used by both the sender and the recipient of
a datagram packet to send and receive a packet, respectively. There are two types of constructors for
DatagramSocket:
METHODS
public DatagramPacket(byte[] buffer, int length)-Creates a datagram packet for receiving a packet
of the specified size. The buffer will contain the incoming packet. The array of bytes passed in to
these constructors is used to contain the data of the incoming packet, and typically are empty arrays.
public DatagramPacket(byte[] buffer, int length, InetAddress address, int port)- Creates a
datagram packet for sending a packet of the specified size. The buffer contains the data of the
packet, and the address and port denote the recipient.
METHODS
DatagramPacket has five methods that retrieve different parts of a datagram: the
actual data plus several fields from its header. These methods are mostly used for datagrams you
receive from the network.
public int getPort( ) -The getPort() method returns an integer specifying the remote port. If this
datagram was received from the Internet, this is the port on the host that sent the packet. If the
datagram was created locally to be sent to a remote host, this is the port to which this packet is
addressed on the remote machine.
public byte[ ] getData( )- The getData() method returns a byte array containing the data from the
datagram.
public int getLength( )-The getLength() method returns the number of bytes of data in the
datagram
public int getOffset( ) - This method simply returns the point in the array returned by getData()
where the data from the datagram begins
Java also provides four methods for changing the data, remote address, and remote port after the
datagram has been created
public void setData(byte [] buffer)-This method can be used to set the data of the packet.
public void setLength(int length)- Sets the length of the data to be sent or received.
public void setSocketAddress(SocketAddress address)-Sets the address of the remote host where
the message is being sent to or received from
1. Create an array of bytes large enough to hold the data of the incoming packet.
3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost address, if
necessary) on the localhost the socket will bind to.
4. The receive() method of the DatagramSocket class is invoked, passing in the DatagramPacket
object. This blocks the execution of further code until a datagram packet is received or a time
out occurs
EXAMPLE:
import java.net.*;
import java.io.*;
public class PacketReceiver
{
public static void main(String [] args) throws Exception
{
byte [] buffer = new byte[1024];
DatagramPacket packet =
new DatagramPacket(buffer, buffer.length);
DatagramSocket socket = new DatagramSocket(5002);
System.out.println(“Waiting for a packet...”);
socket.receive(packet);
System.out.println(“Just received packet from “+ packet.getSocketAddress());
buffer = packet.getData();
System.out.println(new String(buffer));
}
}
1. Create an array of bytes large enough to hold the data of the packet to be sent, and fill the array
with the data.
4. The send() method of the DatagramSocket class is invoked, passing in the DatagramPacket
object.
EXAMPLE:
import java.net.*;
import java.io.*;
public class PacketSender
{
public static void main(String [] args)
{
try
{
String data =
“You have just received a packet of data sent using UDP”;
byte [] buffer = data.getBytes();
DatagramPacket packet =
new DatagramPacket(buffer,buffer.length, InetAddress.getLocalHost(), 5002);
DatagramSocket socket = new DatagramSocket(5003);
System.out.println(“Sending a packet...”);
socket.send(packet);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
EXAMPLE:
URL stands for Uniform Resource Locator, represents a resource on the World
Wide Web, such as a Web page or FTP directory. A URL can be broken down into parts, as follows:
protocol://host:port/path?query#ref
Eg:http://www.javapassion.com:80/javaintro/index.html#Networking_A
scheme or Internet protocol to be followed. e.g. http, https, ftp, mailto, etc. Yes
protocol This defines the syntax of the URL.
domain or This is the destination location for the URL. It can be a Yes
hostname hostname or ip address
Query string This is the data to be passed to software running on the server. No
or search
(Table:4.1)
The java.net.URL class represents a URL. The URL class has several constructors for creating
URLs
public URL(String protocol, String host, int port, String file)-Creates a URL by putting together
the given parts
public URL(String url)- Creates a URL from the given String. The URL class contains many
methods for accessing the various parts of the URL being represented
The URL class contains many methods for accessing the various parts of the URL being represented.
Some of the methods in the URL class include the following:
EXAMPLE:
import java.net.*;
import java.io.*;
public class URLDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL(args[0]);
System.out.println("URL is:" + url.toString());
System.out.println("protocol is:"+ url.getProtocol());
System.out.println("file name is:" + url.getFile());
System.out.println("host is:" + url.getHost());
System.out.println("path is:" + url.getPath());
System.out.println("port is:" + url.getPort());
System.out.println("query is:" + url.getQuery());
OUTPUT
Java http://www.example.com:80/example.php?y=2#results
URL is:http://www.example.com:80/example.php?y=2#results
protocol is:http
file name is:/example.php?y=2
host is:www.example.com
path is:/example.php
port is:80
query is:y=2
ref is:results