Вы находитесь на странице: 1из 12

SILVER OAK COLLEGE OF ENGINEERING & TECHNOLOGY

DEPARTMENT OF COMPUTER ENGINEERING


MODULE-1 SOLUTION

Subject Name: Advance Java Semester: VI


Subject Code: 2160707 Academic Session: Summer’19

Q .1 What is Datagram Socket? Explain in detail with example.


Ans  DatagramSocket's are Java's mechanism for network communication via UDP
instead of TCP. You can use Java's DatagramSocket both for sending and
receiving UPD datagrams.
 With UDP you just send packets of datagrams to some IP address on the
network. You have no guarantee that the data will arrive. You also have no
guarantee about the order which UDP packets arrive in at the receiver. This
means that UDP has less protocol overhead (no stream integrity checking) than
TCP.
 UDP is appropriate for data transfers where it doesn't matter if a packet is lost in
transition. For instance, imagine a transfer of a live TV-signal over the internet.
 Sending Data via a DatagramSocket
o To send data via Java's DatagramSocket first a DatagramPacket is
created.

byte[] buffer = new byte[65508];


InetAddress address = InetAddress.getByName("www.socet.edu.in");

DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 9000);

 The byte buffer (the byte array) is the data that is to be sent in the UDP
datagram. The length of the above buffer, 65508 bytes, is the maximum amount
of data you can send in a single UDP packet.
 The InetAddress class represents an IP address (Internet
Address).The getByName() method returns an InetAddress instance with the IP
address matching the given host name.
 To send the DatagramPacket you must create a DatagramSocket targeted at
sending data. Here is how that is done:
DatagramSocket datagramSocket = new DatagramSocket();

DatagramPacket packet = new DatagramPacket( buffer, buffer.length,


receiverAddress, 80);
datagramSocket.send(packet);

 Receiving Data via a DatagramSocket


o Receiving data via a DatagramSocket is done by first creating
a DatagramPacket and then receiving data into it via
the DatagramSocket's receive() method.
DatagramSocket datagramSocket = new DatagramSocket(80);

byte[] buffer = new byte[10];


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

datagramSocket.receive(packet);

 The DatagramSocket is instantiated with the parameter value 80 passed to its


constructor. This parameter is the UDP port the DatagramSocket is to receive
UDP packets on.
 The DatagramPacket has no information about the node to send data to, as it
does when creating a DatagramPacket for sending data. This is because we are
going to use the DatagramPacket for receiving data. Thus no destination address
needed.

 Example of Sending DatagramPacket by DatagramSocket

import java.net.*;

public class DSender{

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

DatagramSocket ds = new DatagramSocket();

String str = "Welcome java";

InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(),


ip, 3000);
ds.send(dp);
ds.close();
}
}

 Example of Receiving DatagramPacket by DatagramSocket

import java.net.*;
public class DReceiver{

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

DatagramSocket ds = new DatagramSocket(3000);


byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}

Q.2 Explain Socket, ServerSocket, InetAddress classes.

Ans
Socket:

 A socket 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..
 Socket classes are used to represent the connection between a client program and a
server program.
 The java.net package provides two classes--Socket and ServerSocket--that implement
the client side of the connection and the server side of the connection, respectively.
 For creating a socket on the client side two arguments are required as under:

Socket socket = new Socket("hostname/IP address", port no);

 For writing data to a Socket an OutputStream is obtained as under:

Socket socket = new Socket("www.socet.edu.in",8080);

OutputStream out = socket.getOutputStream();

 For reading data from a Socket an IntputStream is obtained as under:

Socket socket = new Socket("www.socet.edu.in", 8080);

InputStream in = socket.getInputStream();

 Closing a Socket

When you are done using a Java Socket you must close it to close the
connection to the server. This is done by calling the Socket.close() method

socket.close();

ServerSocket: In order to implement a Java server that listens for incoming connections
from clients via TCP/IP, java.net.ServerSocket is to be used.

 Creating a ServerSocket

Here is a simple code example that creates a ServerSocket that listens on port
9000:
ServerSocket serverSocket = new ServerSocket(9000);

 Listening For Incoming Connections

In order to accept incoming connections you must ServerSocket’s


accept() method is called. The accept()method returns a Socket which behaves like an
ordinary Socket.

ServerSocket serverSocket = new ServerSocket(9000);

Socket clientSocket = serverSocket.accept();

 Incoming connections can only be accepted while the thread running the server
has called accept(). All the time the thread is executing outside of this method no
clients can connect.

InetAddress:

 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, and
more.

public final class InetAddress extends Object implements Serializable

 Above class represents an Internet address as two fields: hostName (a String)


and address (an int).
 hostName contains the name of the host; for example, www.google.com.
 address contains the 32-bit IP address.
 These fields are not public, so you can’t access them directly. It will probably be
necessary to change this representation to a byte array when 16-byte IPv6
addresses come into use.

Q.3 Write a java program to find an IP address of the machine on which the program
runs.
Ans Program:

import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.gmail.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}

Q.4 Write TCP or UDP program to perform the following:


client> java client localhost/IP Port <enter>
Enter text: This is my text to be changed by the SERVER
<enter>
Response from server: REVRES EHT YB DEGNAHC EB OT TXET YM SI SIHT
client> exit
Ans TCP_Client:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TCP_Client {

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


{
Socket s=new Socket("localhost",5335);

InetAddress host=InetAddress.getLocalHost();
System.out.println("java client"+host);

System.out.println("Enter String");
BufferedReader client=new BufferedReader(new InputStreamReader(System.in));
String data=client.readLine();

PrintWriter out=new PrintWriter(s.getOutputStream(),true);


out.println(data);

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


String str1=br.readLine();
System.out.println("Reverse string: "+str1);
}
}

TCP_Server:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP_Server {


public static void main(String argv[]) throws Exception
{
System.out.println("Server is started...");
ServerSocket ss= new ServerSocket(5335);

System.out.println("Server is waiting for client request...");


Socket s=ss.accept();

System.out.println("Connection established...");

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


String cd=br.readLine();

StringBuffer data=new StringBuffer(cd);


PrintWriter out=new PrintWriter(s.getOutputStream());
String rever=data.reverse().toString();
out.println(rever);
out.flush();
}
}

Output:

Server:

Server is started...
Server is waiting for client request...
Connection established...

Client:

java clientLenovo-PC/127.0.0.1
Enter string:
This is my text to be changed by the SERVER
Reverse string: REVRES eht yb degnahc eb ot txet ym si sihT

Q.5 What is JDBC? List various types of JDBC Driver. Explain thick and thin driver.
Write code snippet for any type of JDBC connection. Comment on selection of
driver.
Ans
JDBC:
 The Java Database Connectivity (JDBC) API is the industry standard for
database-independent connectivity between the Java programming language and
a wide range of databases SQL databases and other tabular data sources, such as
spreadsheets or flat files.
 The JDBC classes are contained in the Java Package java.sql and javax.sql.
JDBC helps you to write Java applications that manage these three programming
activities:
1. Connect to a data source, like a database.
2. Send queries and update statements to the database.
3. Retrieve and process the results received from the database in answer to the
query.
JDBC Drivers Types:-

JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun Microsystems has divided the
implementation types into four categories, Types 1,2, 3, and 4, which are as under :

Type 1: JDBC-ODBC Bridge Driver


Type 2: JDBC-Native API
Type 3: JDBC-Net pure Java
Type 4: Pure Java

Thick Driver:

 This was the second JDBC driver introduced by Java after Type 1, hence it
known as type 2.
 In this driver, performance was improved by reducing communication layer.
Instead of talking to ODBC driver, JDBC driver directly talks to DB client using
native API. That's why it is also known as native API or partly Java driver or
thick driver.
 Type 2 drivers wrap a thin layer of Java around database-specific native code
libraries.
 Since it required native API to connect to DB client it is also less portable and
platform dependent.
 If native library e.g. ocijdbc11.dll, which is required to connect Oracle
11g database is not present in client machine then you will get error.
 For Oracle databases, the native code libraries might be based on the OCI
(Oracle Call Interface) libraries, which were originally designed for C/ C++
programmers. Because
 Type 2 drivers are implemented using native code; in some cases they have
better performance than their all-Java counterparts.
 They add an element of risk; however, because a defect in a driver’s native code
section can crash the entire server.
Code Snippet:

public static void main(String args[])


{
String url="jdbc:oracle:oci:@192.168.1.12:1521:xe";
String uname=”root”;
String pass=”socet”;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Native-API (OCI) driver
Connection con = DriverManager.getConnection(url,uname,pass);
System.out.println("Connected Successfully To Oracle using OCI
driver");
con.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

Thin Driver :

 This is the driver which is most likely to be used to connect to modern database
like Oracle, SQL Server, MySQL, SQLLite and PostgreSQL.
 This driver is implemented in Java and directly interacts with the database using
its native protocol.
 This driver includes all database call in one JAR file, which makes it very easy
to use. All that is needed to connect a database from Java program is to include
JAR file of relevant JDBC driver.
 Because of light weight, this is also known as thin JDBC driver.
 Since this driver is also written in pure Java, it is portable across all platform,
which means you can use same JAR file to connect to MySQL even if your Java
program is running on Windows, Linux or Solaris.
 Performance of this type of JDBC driver is also best among all of them.

Code Snippet:

public static void main(String args[])


{
String url="jdbc:oracle:thin:@localhost:1521:xe";
String uname=”root”;
String pass=”socet”;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
Connection con = DriverManager.getConnection(url,uname,pass);
System.out.println("Connected Successfully To Oracle");
con.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

Comment on selection of driver:

Type 4 JDBC driver is the most preferable driver. There is hardly any situation when
you need to go to previous version of JDBC driver. Though, if you want to connect to
Oracle database using TNS name using OCI client, you need to use type 2 JDBC driver
also known as thick JDBC driver. That requires database native client library
e.g. ocijdbc11.dll and if that's not present in the machine then your Java program will
throw error at run time.
Q.6 Explain JDBC Architecture.
Ans  As shown in the figure, the java application that needs to communicate with a
database has to be programmed using JDBC API.
 The JDBC driver supporting data source, such as Oracle and SQL has to be
added in java application for JDBC support, which can be done dynamically at
run time.
 The dynamic plugging of the JDBC drivers ensures that the Java application is
vendor independent.
 Some of the available drivers are pure Java drivers and are portable for all
environments; whereas others are partial java drivers and require some libraries
to communicate with the database.
 The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
 The JDBC API is defined in java.sql package and it consists of the following
interfaces or classes:
Figure: JDBC Architecture

 DriverManager:- The JDBC driver manager ensures that the correct driver is
used to access each data source.

 Driver: A JDBC driver is required to process the SQL requests and generate
results. There are 4 types of JDBC drivers as specified by Sun Microsystems:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (Pure java driver)

 Connection:-Connection class creates objects which represents connection and


it's object also helps in creating object of Statement, PreparedStatement and
CallableStatement classes.

 Statement:- Statement object is used to execute query and also store it's value to
"Resultset" object.

 PreparedStatement:-It can be used in place of Statement. PreparedStatement's


performance is high as compared to Statement class, represents a precompiled
SQL statement.

 Callable Statement:-Callable statement support stored procedure of RDBMS'


using it's object you can execute stored procedure of database application.

 ResultSet:- Resultset object is used to store the result retrieve from database
using Statement, PreparedStatement etc.

 SQLException:- SQLException class is used to represent error or warning


during access from database or during connectivity.

Q.7 Explain JDBC URL with appropriate example.


Ans When working with a database system via JDBC, the following information is required
for making connection to the database:
 Driver class name:
It is name of the class that implements java.sql.Driver interface. The JDBC’s
driver manager needs to load this class in order to work with the database driver.

 Database URL: a string that contains information about the database to connect
to and other configuration properties. This string has its own format and is varied
among different databases.
Following are the examples of JDBC URL for MySQL and Oracle database:

1. MySQL

Driver class name: com.mysql.jdbc.Driver


Format of database URL: jdbc:mysql://[host][,failoverhost...][:port]/[database]
[?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...

Examples:

 jdbc:mysql://localhost:3306/world
 jdbc:mysql://localhost:3306/world?user=root&password=socet

2. Oracle

Driver class name: oracle.jdbc.OracleDriver

Format of database URL:

jdbc:oracle:<drivertype>:@<database>
jdbc:oracle:<drivertype>:<user>/<password>@<database>

where drivertype can be thin or oci.

Examples:

 jdbc:oracle:thin:@localhost:1521:test
 jdbc:oracle:thin:root/socet@localhost:1521:test

Вам также может понравиться