Unit 1

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

Advanced Java Course Outcomes

Students will be able to


Compare connection-oriented and
CO603.1 connection-less client server communication
applications
Execute program to make connection
CO603.2 between java application and database
Course
using JDBC
Outcomes
Implement server side programming with
(Cos) CO603.3
Java Servlet
CO603.4 Utilize JSP & JSF to design web pages.
Illustrate the concepts of Hibernate
CO603.5
framework
CO603.6 Demonstrate the Spring MVC Architecture.
UNIT 1: Java Networking
Network Basics
• A network represents interconnection of
computers and devices either by using cable or
satellite link where no cable required.
• In a network, there may be several computers
among which some of them must be receiving
the services and some providing the services to
others.
• There are 3 requirements to establish a network,
namely hardware, software and protocol.
Network Basics
• TCP/IP Suite
• UDP
• Port and socket
• URL
Network Basics
• Network Programming involves writing programs that
communicate with other programs across a computer
network.
• JAVA makes networking applications simple due to the
easy-to-use libraries.
• A server is an application that provides a "service" to
various clients who request the service.
• In the general networking scenario, everybody can
either be a client or a server at any time.
• This is known as peer-to-peer computing. In terms of
writing java applications it is similar to having many
applications communicating among one another.
import java.net.*;
Classes
InetAddress

URL

URLConnection
Socket
ServerSocket
DatagramSocket
DatagramPacket
Network Basics
• internet communication is built of several layers:
• When you write JAVA applications that communicate over a network, you
are programming in the Application Layer.
• JAVA allows two types of communication via two main types of Transport
Layer protocols:
TCP vs UDP 8

TCP is a connection-oriented protocol. UDP is a connectionless protocol.


TCP is suited for applications that UDP is suitable for applications that
require high reliability, and need fast, efficient transmission, such
transmission time is relatively less as games. UDP's stateless nature is
critical. also useful for servers that answer
small queries from huge numbers of
clients.
HTTP, HTTPs, FTP, SMTP, Telnet DNS, DHCP, TFTP, VOIP.
The speed for TCP is slower than UDP. UDP is faster because there is
no error- checking for packets.
There is absolute guarantee that the There is no guarantee that the
data transferred remains intact and messages or packets sent would
arrives in the same order in which it reach at all.
was sent.
TCP header size is 20 bytes UDP Header size is 8 bytes.
Data is read as a "stream," with Datagrams: Packets are sent individually
nothing distinguishing where one and
packet ends and another begins. are guaranteed to be whole if they arrive.
Ports
• Data transmitted over the Internet is accompanied by
addressing information that identifies the computer
and the port for which it is destined.
• Ports are identified by a 16-bit number, which TCP and
UDP use to deliver the data to the right application.
• The TCP and UDP protocols use ports to map incoming
data to a particular process running on a computer.
• A distinct port number is used for every new process
from the range 0 to 65535 out of which first initial port
numbers are reserved for well-known applications.
InetAddress Class

• Java InetAddress class represents an IP


address. The java.net.InetAddress class
provides methods to get the IP of any host
name.
InetAddress Class
• No public constructor
• Three static methods:
– InetAddress getByName(String)
• Static method used to retrieve the address for the host name
passed as the parameter.
– public String getHostAddress()
• It returns the IP address in string format.
– public String getHostName()
• It returns the host name of the IP address.
– byte[ ] getAddress( )
• Returns the IP address.
– InetAddress getLocalHost( )
• Static method used to retrieve the address for the current, or
local, host.
InetAddress Examples
class Address
{ public static void main(String args[ ]) throws IOException
{

Scanner sc=new Scanner(System.in);


System.out.print("Enter a website name: ");
String url = sc.nextLine();
try{
InetAddress ip = InetAddress.getByName(site);
System.out.println("The IP Address is: "+ ip);
}catch(UnknownHostException ue) {
System.out.println("Website not found");
}
}
}
URL
• URL is an acronym for Uniform Resource Locator.
• The Java URL class represents an URL.
• It points to a resource on the World Wide Web. For example:

• A URL contains many information:


• Protocol: In this case, http is the protocol.
• Server name or IP Address: In this case, www.javatpoint.com is the server
name.
• Port Number: It is an optional attribute. If we write
http//www.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port
number is not mentioned in the URL, it returns -1.
• File Name or directory name: In this case, index.jsp is the file name.
JAVA URL class
• The URL class is present in the java.net package.
• To create an URL object,
• URL(String protocol, String host, int port, String file)
• Creates an instance of a URL from the given protocol,
host, port number, and file.
• URL(String protocol, String host, String file)
• Creates an instance of a URL from the given protocol
name, host name, and file name.
JAVA URL class
Method Description

public String getProtocol() it returns the protocol of the URL.


public String getHost() it returns the host name of the
URL.
public String getPort() it returns the Port Number of the
URL.
public String getFile() it returns the file name of the
URL.
Public String getPath() It returns the file path of the URL
29

Example of URL
• import java.io.*; import
java.net.*;
• public class URLDemo{
• public static void main(String[] args){
• try{
• URL url=new
URL("https://retail.axisbank.co.in/wps/portal/
rBanking/axisebanking/AxisRetailLogin") ;
• System.out.println("Protocol: "+url.getProtocol());
• System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
• }catch(Exception e){System.out.println(e);}
• }
• }
30

Output
Socket Programming
• Java Socket programming is used for
communication between the applications running
on different JRE.
• Java Socket programming can be connection-
oriented or connection-less.
• Socket and ServerSocket classes are used for
connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
Socket Programming
• The client in socket programming must know
two information:
• IP Address of Server, and
• Port number.
JAVA TCP Sockets
• java.net.Socket
– Implements client sockets (also called just “sockets”).
– An endpoint for communication between two machines.
– Constructor and Methods
• Socket(String host, int port): Creates a stream socket and
connects it to the specified port number on the named host.
• InputStream getInputStream() : returns the InputStream
attached with this socket.
• OutputStream getOutputStream() : returns the
OutputStream attached with this socket.
• close() : closes this socket
• InetAddress getInetAddress();
• InetAddress getLocalAddress();
JAVA TCP Sockets
• java.net.ServerSocket
– Implements server sockets.
– Waits for requests to come in over the network.
– Performs some operation based on the request.
– Constructor and Methods
• ServerSocket(int port)
• Socket Accept(): Listens for a connection to be made to this
socket and accepts it. This method blocks until a connection
is made.
• InputStream getInputStream()
• OutputStream getOutputStream()
• InetAddress getInetAddress();
• int getLocalPort();
Stream Based Connection
Socket I/O
• Socket I/O is based on the Java I/O support
– in the package java.io

• InputStream and OutputStream are abstract


classes
– common operations defined for all kinds of
InputStreams, OutputStreams…
InputStream Basics
// reads some number of bytes and
// puts in buffer array b
int read(byte[] b);

// reads up to len bytes


int read(byte[] b, int off, int
len);

Both methods can throw IOException.


Both return –1 on EOF.
OutputStream Basics
// writes b.length bytes
void write(byte[] b);

// writes len bytes starting


// at offset off
void write(byte[] b, int off, int
len);

Both methods can throw IOException.


JAVA TCP Sockets
Client/server socket interaction: TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
connectionSocket = clientSocket =
welcomeSocket.accept() Socket()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
• import java.io.*;
• import java.net.Socket;
• public class client {
• public static void main(String[] args) {
• try{
• Socket s=new Socket("localhost",6666);
• DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
• DataInputStream dis=new
DataInputStream(s.getInputStream());
• System.out.println("Connected to server.");
• dout.writeUTF("Hello Server");
• String str=din.readUTF();
• System.out.print("Server says"+str);
• dout.close();
• s.close();
• }catch(Exception e){System.out.println(e);}
• } }
• import java.io.*;
• import java.net.*;
• public class server {
• public static void main(String[] args){
• try{
• ServerSocket ss=new ServerSocket(6666);
• Socket s=ss.accept(); //establishes connection
• System.out.println("Connection established");
• DataInputStream dis=new
DataInputStream(s.getInputStream());
• DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
• String str=(String)dis.readUTF();
• System.out.println("message from client= "+str);
• dout.writeUTF(“Hello Client);
• ss.close();
• }catch(Exception e){System.out.println(e);}
• }
• }
Socket Programming with UDP
• UDP
– Connectionless and unreliable service.
– There isn’t an initial handshaking phase.
– Doesn’t have a pipe.
– transmitted data may be received out of order, or lost

• Socket Programming with UDP


– No need for a welcoming socket.
– No streams are attached to the sockets.
– the sending hosts creates “packets” by attaching the IP destination
address and port number to each batch of bytes.
– The receiving process must unravel to received packet to obtain the
packet’s information bytes.
• Java DatagramSocket class
• Java DatagramSocket class represents a
connection-less socket for sending and receiving
datagram packets. It is a mechanism used for
transmitting datagram packets over network.`
• Java DatagramPacket Class
• Java DatagramPacket is a message that can be
sent or received. It is a data container. If you send
multiple packet, it may arrive in any order.
Additionally, packet delivery is not guaranteed.
23

DatagramSocket
Constructors:
• DatagramSocket()
• DatagramSocket(int port)
• Methods:
• void receive(DatagramPacket p) - It receives the datagram
packet from the socket.
• void send(DatagramPacket p) - It sends the datagram packet
from the socket.
• void close()
Constructors: DatagramPacket 24

• DatagramPacket(byte data[ ], int size)


• DatagramPacket(byte data[ ], int offset, int size)
• DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)
• DatagramPacket(byte data[ ], int offset, int size, InetAddress
ipAddress, int port)
Methods:
• byte[] getData();- It returns the data buffer.
• void setData(byte[] buf);- It sets the data buffer for the packet.
• void setAddress(InetAddress a); - It sets the IP address of the machine to
which the datagram is being sent.
• void setPort(int port);-It sets the port number on the remote host to which
the datagram is being sent.
• InetAddress getAddress();-It returns the IP address of the machine to
which the datagram is being sent or from which the datagram was received.
• int getPort(); - It returns the port number on the remote host to which the
datagram is being sent or from which the datagram was received.
Example: UDPSender 25

class UDPSender {
public static void main (String argv[]) throws Exception {
Scanner sc=new Scanner(System.in);
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getByName("127.0.0.1");//IP of server
byte[] sendData = new byte[1024];
System.out.println(“Enter String to send”);
String str = sc.nextLine();
sendData = str.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData,sendData.length,ip,7777);
ds.send(sendPacket);
ds.close();
}
}
Example: UDPReceiver 26
Class UDPReceiver {
public static void main (String argv[]) throws Exception {
DatagramSocket serverSocket = new
DatagramSocket(7777);
byte[] receiveData = new byte[1024];
while(true) {
DatagramPacket receivePacket = new DatagramPacket
(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
String str = new String(receivePacket.getData());
System.out.println(str.trim());
InetAddress ip = receivePacket.getAddress();
System.out.print("IPAddress of Sender"+ip);
}
}
}
Chatclient(TCP)
public class chatclient {
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new
DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
Scanner sc=new Scanner(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
chatclient
str=sc.nextLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
din.close();
s.close();
}
}
Chatserver(TCP)
import java.io.*;
import java.net.*;
public class chatserver {
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new
DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
Scanner sc=new Scanner(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
Chatserver
str=din.readUTF();
System.out.println("client says: "+str);
str2=sc.nextLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
FileClient
class FileClient{
public static void main(String args[])
throws Exception{
Socket s = new Socket("127.0.0.1",3000);
DataOutputStream dos = new
DataOutputStream(s.getOutputStream());
System.out.print("Enter the file name");
Scanner sc = new Scanner(System.in));
String fname=sc.nextLine();
dos.writeUTF(fname);
FileClient
FileReader fr= new FileReader(fname);
BufferedReader br1=new BufferedReader(fr);
String str1;
dos.flush();

while((str1=br1.readLine()) != null)
{

System.out.print(str1);

dos.writeUTF(str1);

}
System.out.println(“File Transferred”);
br1.close();
s.close();
}
}
FileServer
class FileServer {
public static void main(String args[]) throws
Exception
{
ServerSocket ss = new ServerSocket(3000);
Socket s = ss.accept();
System.out.print("connection done");
DataInputStream dis = new DataInputStream(
s.getInputStream());
FileServer

String filename = dis.readUTF();


System.out.print(filename);
String data=dis.readUTF(); System.out.print(data);
File f1=new File(“c:\\"+filename);
FileWriter fw = new FileWriter(f1);
fw.write(data);
System.out.print("DONE");
fw.flush();
fw.close();
ss.close();
s.close();
}
}
ThreadServer
public class ThreadServer {
static int host;
public static void main(String a[])
{
try{
ServerSocket ss= new ServerSocket(7777);
while(true){
Socket s =ss.accept();
Runnable r = new ThreadedEcho(s);
Thread t = new Thread(r);
t.start();
host++;
}
}
catch(IOException e) { }
} }
class ThreadedEcho implements Runnable
{
Socket in;
public ThreadedEcho(Socket i)
{
in=i;
}
public void run()
{
try{
DataInputStream is=new DataInputStream(in.getInputStream());
DataOutputStream os=new DataOutputStream(in.getOutputStream());
String str=is.readUTF();
System.out.println("Massage from Client "+ThreadServer.host+": "+str);
os.writeUTF(str.toUpperCase());
}
catch(IOException e)
{ System.out.print(“Not Connected”);}
}
}
public class TClient TClient
{
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",7777);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
DataInputStream din=new DataInputStream(s.getInputStream());
System.out.println("Connected to server.");
Scanner sc=new Scanner(System.in);
System.out.println("Enter String to send:");
String str=sc.nextLine();
dout.writeUTF(str);
String str1=din.readUTF();
System.out.print("Server says:"+str1);
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Java URLConnection class
• The Java URLConnection class represents a
communication link between the URL and the
application.
• This class can be used to read and write data to the
specified resource referred by the URL.
• The openConnection() method of URL class returns
the object of URLConnection class.
• Syntax:
public URLConnection openConnection()throws IO
Exception{}
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/ja
va-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e)
{System.out.println(e);}
}
}
URLConnection 31

public class URLConn {


public static void main(String[] args){ try{
URL url=new URL("http://www.internic.net");
URLConnection ulc=url.openConnection(); long d = ulc.getDate();
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));

System.out.println("Content-Type: " + ulc.getContentType());


d = ulc.getExpiration();
if(d==0)
System.out.println("No date information."); else
System.out.println("Date: " + new Date(d));
d = ulc.getLastModified();
if(d==0)
System.out.println("No last-modified information.");
else
System.out.println("Last-Modified: " + new Date(d));
int len = ulc.getContentLength(); if(len == -1)
System.out.println("Content length unavailable."); else
System.out.println("Content-Length: " + len);
if(len != 0) {
System.out.println("=== Content ===");
InputStream input = ulc.getInputStream(); int i = len;
int c;
while (((c = input.read()) != -1))
{
System.out.print((char) c);
}
input.close();
}
else
{
System.out.println("No content available.");
}
catch(Exception e)
{System.out.println(e);}
URLConnection 32
RMI
• The RMI (Remote Method Invocation) is an
API that provides a mechanism to create
distributed application in java. The RMI allows
an object to invoke methods on an object
running in another JVM.
• The RMI provides remote communication
between the applications using two
objects stub and skeleton.
35

RMI
36

RMI
37

RMI
38

Example: AdditionInterface
import java.rmi.*;

public interfaceAdditionInterface extends Remote


{
public int addition(int a, int b) throws RemoteException;
}
Example: AdditionClass 39

import java.rmi.*;
import java.rmi.server.*;

public class AdditionClass implements AdditionInterface


{

AdditionClass()
{
}
public int addition(int a, int b)
{
return (a+b);
}
}
Example: Server 40

public class server extends AdditionClass


{
public static void main(String args[]) throws RemoteException
{
try{
System.out.println("Binding started"); AdditionInterface
srobj=new AdditionClass();
AdditionInterface stub = (AdditionInterface)
UnicastRemoteObject.exportObject(srobj,0);
Registry registry=LocateRegistry.createRegistry(8888);
registry.rebind("add",stub);
System.out.println("Binding completed");
System.out.println("Waiting for client");
}
catch(Exception e){ }
}
Example: Client
class client { 4
1
public static void main(String args[])
{ try{
Scanner sc=new Scanner(System.in);
System.out.print("Enter no1");
int no1=sc.nextInt(); System.out.print("Enter no2");
int no2=sc.nextInt();
Registry registry = LocateRegistry.getRegistry(8888);
AdditionInterface obj = (AdditionInterface) registry.lookup("add");
System.out.println("Addition = " + obj.addition(no1,no2));
}
catch(Exception e)
{
e.printStackTrace();
}
}}

You might also like