java_notes

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

Networking Basics

• Networking is the process of connecting two or more computing devices together so that data and resources
can be shared.
• LAN: local area network: group of network devices connected together within a same building or organization.
• MAN: metropolitan area network: is a larger network spans several buildings in a same city or town.
• WAN: wide area network: is a larger network than MAN, spans large geographical region.
• WWW: world wide web is an information space where documents and other web resources are identified by
Uniform Resource Locators (URLs), interlinked by hypertext links, and accessible via the internet.
• A key component of the Internet is the address (IP). An IP address is a number that uniquely identifies each
computer on the Net.
• Originally, all Internet addresses consisted of 32-bit values, organized as four 8-bit values in a range (0,255).
This address type was specified by IPv4 (Internet Protocol, version 4). However, a new addressing scheme,
called IPv6 (Internet Protocol, version 6) has come into play. IPv6 uses a 128-bit value to represent an address,
organized into eight 16-bit chunks.
• Many computers can also be referred to by domain names
• One of IP’s is the loopback address, which can be used when a program wants to communicate with another
program on the same computer. The loopback address has IPv4 address 127.0.0.1 and can also, in general, be
referred to using the domain name localhost
Networking Basics
• MAC address is a unique identifier of NIC
• Port number is used to uniquely identify different applications.

• Now, a single computer might have several programs doing network communication at the same time, or one program
communicating with several other computers. To allow for this possibility, a network connection is actually identified by
a port number in combination with an IP address which called socket address.
• Socket is an application program responsible for communication between two end points. A socket is uniquely identify by
an IP address and a port.
• A server does not simply listen for connections—it listens for connections on a particular port. A potential client must
know both the Internet address (or domain name) of the computer on which the server is running and the port number on
which the server is listening.

• java.net: This package includes several classes that can be used for networking.
• The main classes for this style of networking are java.net.URL and java.net.URLConnection.
Networking Basics
• An object of type URL is an abstract representation of a Universal Resource Locator, which is an address for an HTML
document or other resource on the Web.
• A URLConnection represents a network connection to such a resource.

• An object belonging to the URL class represents such an address. Once you have a URL object, you can use it to open a
URLConnection to the resource at that address. A url is ordinarily specified as a string, such as
“http://math.hws.edu/eck/index.html”
• Once you have a valid URL object, you can call its openConnection() method to set up a connection. This method returns
a URLConnection. The URLConnection object can, in turn, be used to create an InputStream for reading data from the
resource represented by the URL. This is done by calling its getInputStream() method. For example:
• URL url = new URL(urlAddressString);

• URLConnection connection = url.openConnection();


• InputStream in = connection.getInputStream();
• The openConnection() and getInputStream() methods can both throw exceptions of type IOException. Once the
InputStream has been created, you can read from it in the usual way
import java.net.*;
public class URLdemo
{
public static void main(String args[])
{
try
{
URL url = new URL("https://www.ugc.gov.in:443/Notices");
System.out.println(url.getProtocol()); //https
System.out.println(url.getHost()); //www.ugc.gov.in
System.out.println(url.getPort()); //443
System.out.println(url.getFile()); //URL-class
} catch(Exception e){System.out.println(e);}
}
}
import java.net.*;
import java.io.*;
public class URLConnectionDemo
{
public static void main(String args[])
{
try
{
URL url = new URL("https://www.javatpoint.com/InetAddress-class");

URLConnection uc = url.openConnection();
InputStream s = uc.getInputStream();
int b;
while((b=s.read())!=-1)
System.out.println((char)b);
} catch(Exception e){System.out.println(e);}
}
}
import java.net.*;
import java.io.*;
class InetAddressDemo
{
public static void main(String args[])
{
try
{
InetAddress ip = InetAddress.getByName("www.google.in");
System.out.println("name: " + ip.getHostName());
System.out.println("ip:" + ip.getHostAddress());

} catch(Exception e){System.out.println(e);}
}
}
Communication
For the networking with java, it provides two types of sockets:
Stream sockets and datagram sockets.
1. Stream Sockets:
• With stream sockets a process establishes a connection to another process.
• Here, stream sockets are said to provide a connection-oriented service.
• The protocol used is TCP(Transmission Control Protocol)

2. Datagram Sockets:
• With datagram sockets, individual packets of information are transmitted.
• The transmission of packets follows a connection less service
• The protocol used is UDP (User Datagram Protocol)
Client/Server model of network communication using TCP
• TCP communication based on the concept of Client/Server model. It allows bi-directional point-to-point,
stream based connection between two machines one of which is termed as sever and other being the client.
• The idea is that the server is out there somewhere on the network, waiting for a connection request from some
client. The server can be thought of as offering some kind of service, and the client gets access to that service
by connecting to the server. This is called the client/server model of network communication.
• For two programs to communicate using TCP/IP, each program must create a socket, and those sockets must
be connected.
• Once such a connection is made, communication takes place using input streams and output streams. Each
program has its own input stream and its own output stream.
• Data written by one program to its output stream is transmitted to the other computer. There, it enters the input
stream of the program at the other end of the network connection. When that program reads data from its input
stream, it is receiving the data that was transmitted to it over the network.
• To implement TCP/IP connections, the java.net package provides two classes, ServerSocket and Socket.
These two classes are to establish socket connections between client and server. Sockets in Java are end points
of communication links between processes (which are under run in two machines).
• The Socket class is to create a socket for client and the ServerSocket is for server.
Client/Server model of network communication using TCP
• A ServerSocket represents a listening socket that waits for connection requests from clients.
• A Socket represents one endpoint of an actual network connection.
• A Socket can be a client socket that sends a connection request to a server. But a Socket can also be created by
a server to handle a connection request from a client. This allows the server to create multiple sockets and
handle multiple connections.
• A ServerSocket does not itself participate in connections; it just listens for connection requests and creates
Sockets to handle the actual connections.
• As soon as a ServerSocket is created, it starts listening for connection requests. The accept() method in the
ServerSocket class accepts such a request, establishes a connection with the client, and returns a Socket that
can be used for communication with the client. The accept() method has the form
public Socket accept() throws IOException
• When you call the accept() method, it will not return until a connection request is received (or until some error
occurs). The method is said to block while waiting for the connection
• Once you have a connected socket, no matter how it was created, you can use the Socket methods
getInputStream() and getOutputStream() to obtain streams that can be used for communication over the
connection. These methods return objects of type InputStream and OutputStream, respectively.
Communication using TCP
Server
Client import java.io.*;
import java.net.*;
import java.net.*;
import java.io.*; public class ServerDemo
public class ClientDemo {
{ public static void main(String args[])
public static void main(String args[]) {
{ try
try {
{ ServerSocket ss = new ServerSocket(2355);
Socket s = new Socket("localhost",2355); Socket s = ss.accept();
DataOutputStream dout = new DataOutputStream(s.getOutputStream()); System.out.println("connected");
DataInputStream di = new DataInputStream(s.getInputStream());
dout.writeUTF("Hello");
dout.writeUTF("Hi"); String s1 = (String)di.readUTF();
dout.close(); System.out.println(s1);
s.close(); s1 = (String)di.readUTF();
}catch(Exception e){System.out.println(e);} System.out.println(s1);
} ss.close();
} }catch(Exception e){System.out.println(e);}
}
}
Communication using UDP
• Java implements the communication with UDP protocol using two classes : DatagramPacket
and DatagramSocket.
• The DatagramPacket object is the data container
• while the DatagramSocket is the mechanism used to send or receive the DatagramPackets.

DatagramPackets can be created using one of the two constructors as stated below :
• public DatagramPacket (byte ibuf [ ], int length);
• public DatagramPacket (byte ibuf [ ], int length, InetAddress iaddr, int iport);

The first constructor uses only a byte buffer and a length. It is used for receiving data over a
DatagramSocket.

The second constructor adds target address and port number, which are used by DatagramSocket to
determine where the data in the packet will be sent.
Communication using UDP

Client Server
import java.net.*;
import java.net.*;
import java.io.*;
import java.io.*;
public class ClientData
public class ServerData
{
{
public static void main(String args[])
public static void main(String args[])
{
{
try{
try
DatagramSocket s = new DatagramSocket();
{
String s1 = "Hello GEU";
DatagramSocket ds = new DatagramSocket(2354);
InetAddress ip = InetAddress.getByName("127.0.0.1");
byte b[] = new byte[1024];
DatagramPacket dp = new
DatagramPacket dp = new DatagramPacket(b,1024);
DatagramPacket(s1.getBytes(),s1.length(),ip,2354);
ds.receive(dp);
s.send(dp);
String str = new String(dp.getData(),0,dp.getLength());
s.close();
System.out.println(str);
}
ds.close();
catch(Exception e){System.out.println(e);}
} catch(Exception e){System.out.println(e);};
}
}
}
}
Collections
• The Collection in Java is a framework that provides an architecture to store and manipulate the group of
objects.
• Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
• Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List,
Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
• Collection represents a single unit of objects i.e. a group.
• All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc.
can be performed by Java Collections.
• Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
• Java new generic collection allows you to have only one type of object in a collection. Now it is type-safe, so
typecasting is not required at runtime.
ArrayList
• Java ArrayList class uses a dynamic array for storing the elements.
• It is like an array, but there is no size limit.

• We can add or remove elements anytime. So, it is much more flexible than the traditional array.
• It is found in the java.util package.
• It inherits the AbstractList class and implements List interface.

• Java ArrayList class can contain duplicate elements.


• Java ArrayList class maintains insertion order.
ArrayList<int> al = ArrayList<int>(); // does not work since it is collection of array.

ArrayList<Integer> al = new ArrayList<Integer>(); // works fine


Example 1
import java.util.*;
public class DemoArrayList
{
public static void main(String args[])
{ ArrayList<String> list = new ArrayList<String> (); //Creating arraylist
list.add("Mango"); //Adding object in arraylist
list.add("Banana");
list.add("Grapes");
list.add("Grapes");
System.out.println(list);
list.set(1,"Orange"); //assigning new object
System.out.println(list);
list.remove(1); //Removing object from the arraylist
System.out.println(list);
}
}
Set Interface
• A set is an unordered collection of objects in which duplicate values cannot be
stored. This collection is used when we wish to avoid the duplication of the
objects and wish to store only the unique objects. This set interface is
implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc.

HashSet<String> hs = new HashSet<String >(); //Creating arraylist


list.add("Mango"); //Adding object in arraylist
list.add("Banana");
list.add("Grapes");

System.out.println(list);
Jar
• A JAR (Java Archive) is a package file format typically used to aggregate many Java class
files and associated metadata and resources (text, images, etc.) into one file to distribute
application software or libraries on the Java platform.
• JAR file is a file that contains a compressed version of .class files, audio files, image files,
or directories.
• Create a JAR file
• jar cf jarfilename inputfiles
• View a JAR file
• jar tf jarfilename
• Extracting a JAR file
• jar xf jarfilename
• Updating a JAR File
• jar uf jar-file input-file(s)
• Running a JAR file
• java -jar pack.jar
Applet is a special type of program that is embedded in the webpage to generate
the dynamic content.

Lifecycle of Java Applet

When an applet begins, the following methods are called

When an applet is terminated, the following sequence of method calls takes place:
Applet
• public void init(): is used to initialized the Applet. It is invoked only once.
• public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
• public void paint(Graphics g): this method is called each time an AWT-based applet’s
output must be redrawn.
• public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser
is minimized.
• public void destroy(): is used to destroy the Applet. It is invoked only once.
Servlets
• Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
• Servlet technology is robust and scalable because of java language.
• Java Servlets are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the web server, process the request,
produce the response, and then send a response back to the web server.

Execution of Servlets basically involves Six basic steps:


1. The Clients send the request to the Web Server.
2. The Web Server receives the request.
3. The Web Server passes the request to the corresponding servlet.
4. The Servlet processes the request and generates the response in the form of output.
5. The Servlet sends the response back to the webserver.
6. The Web Server sends the response back to the client and the client browser displays it on the
screen.
Life Cycle of a Servlet
The web container maintains the life cycle of a servlet instance.
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.

• The servlet is in new state if servlet instance is created.


• After invoking the init() method, Servlet comes in the ready state. In
the ready state, servlet performs all the tasks.
• When the web container invokes the destroy() method, it shifts to
the end state.

there are three states of a servlet: new, ready and end.


JDBC
• JDBC stands for Java Database Connectivity.
• JDBC API is used to handle database using Java program and can perform
the following activities:
• Connect to the database
• Execute queries and update statements to the database
• Retrieve the result received from the database.
• JDBC API uses JDBC drivers to connect with the database. There are four
types of JDBC drivers:
1. Type 1 driver : JDBC-ODBC Bridge Driver
2. Type 2 driver: Native Driver
3. Type 3 driver: Network Protocol Driver
4. Type 4 driver: Thin Driver (Pure Java driver)
Java Database Connectivity STEPS
1. Register the Driver class : forName() method of Class class is used to register the driver class. Eg.
Class.forName("com.mysql.jdbc.Driver");
2. Create connection: getConnection() method of DriverManager class is used to establish connection with
the database. E.g: Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/My_Database,“user",“password");
3. Create statement: createStatement() method of Connection interface is used to create
statement. The object of statement is responsible to execute queries with the database. E.g:
Statement stmt=con.createStatement();
4. Execute queries: executeQuery() method of Statement interface is used to execute queries to
the database. This method returns the object of ResultSet that can be used to get all the records
of a table. E.g: ResultSet rs=stmt.executeQuery("select * from emp");
5. Close connection: By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the connection.
E.g.: con.close();
JDBC Driver
• JDBC Driver is a software component that enables java application to interact with the database.
• To connect with individual databases, JDBC (the Java Database Connectivity API) requires drivers for each
database. The JDBC driver gives out the connection to the database and implements the protocol for transferring
the query and result between client and database.
1. Type 1 driver: JDBC-ODBC bridge driver
• The 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.

Advantages:
• easy to use.
• can be easily connected to any database.

Disadvantages:
• Performance degraded because JDBC
method call is converted into the
ODBC function calls.
• The ODBC driver needs to be installed
on the client machine.
Type 2 driver – Native-API driver
• The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.

Advantage:
• performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
• The Native driver needs to be installed on the each client
machine.
• The Vendor client library needs to be installed on client
machine.
Type 3 driver – Network-Protocol driver (middleware
driver)
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
• No client side library is required
because of application server
that can perform many tasks
like auditing, load balancing,
logging etc.

Disadvantages:
• Network support is required on
client machine.
• Requires database-specific coding
to be done in the middle tier.
• Maintenance of Network Protocol
driver becomes costly because it
requires database-specific coding
to be done in the middle tier.
Type 4 driver- Thin driver (Fully Java driver)
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known
as thin driver. It is fully written in Java language.

Advantage:
• Better performance than all other drivers.
• No software is required at client side or server
side.

Disadvantage:
• Drivers depend on the Database.

You might also like