SlideShare a Scribd company logo
1 of 39
mjpatel.cse@vsitr.ac.in
Computer Science Engineering Department
Unit-3 : Java Networking
Vidush Somany institute of Technology & Research, Kadi
Kadi Sarva Vishwavidyalaya , Gandhinagar
 Looping
Outline
 Network Basics
 Networking Terminology
 InetAddress
 URL
 URLConnection
 Client/Server architecture
 Socket overview
 TCP/IP client sockets
 TCP/IP server sockets
 Datagrams
 DatagramsSocket
 DatagramsPacket
Network Basics
 Represent interconnection of computing devices either by using cable or wireless devices for
resources sharing.
 In network, there may be several computers, some of them receiving the services and some
providing services to other.
 The computer which receives service is called a client.
 The computer which provides the service is called server.
A Network is
Networking Terminology
 IP Address : A unique identification number allotted to every device on a network.
 DNS (Domain Name Service) : A service on internet that maps the IP addresses with
corresponding website names.
 Port Number : 2 byte unique identification number for socket.
 URL (Uniform Resource Locator): Global address of document and other resources on the
world wide web.
 TCP/IP: Connection oriented reliable protocol, highly suitable for transporting data reliably on a
network.
 UDP: Transfers data in a connection less and unreliable manner
Network Programming
 The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
 java.net package provides many classes to deal with networking applications in Java
 Here there are few classes related to the connection and then identifying a connection
 InetAddress
 URL
 URLConnection
 For making a actually communication (sending and receiving data) deal with few more classes
like ,
 Socket
 ServerSocket
 DatagramPacket
 DatagramSocket
InetAddress
 InetAddress class belong to the java.net package.
 Using InetAddress class, it is possible to know the IP Address of website / host name
 InetAddress class is used to encapsulate both the numerical IP address and host name for
the address.
Commonly used methods of InetAddress class
Method Description
public static InetAddress getByName(String host)
throws UnknownHostException
Determines the IP address of a given host's name.
public static InetAddress getAllByName (String
host) throws UnknownHostException
It returns an array of IP Addresses that a particular host
name.
public static InetAddress getLocalHost() throws
UnknownHostException
Returns the address of the local host.
public String getHostName() it returns the host name of the IP address.
public String getHostAddress() it returns the IP address in string format.
InetAddress.getByName()
 The getByName() method takes host name (server name) and return InetAddress
 Which is nothing but the IP address of the server.
import java.net.*; //required for InetAddress Class
public class Address{
public static void main(String[] args){
try {
InetAddress ip = InetAddress.getByName(“www.vsitr.ac.in”);
System.out.println("IP: "+ip);
}catch(UnknownHostException e) {
System.out.println(e);
}
}
}
Output
InetAddress.getAllByName()
 The getAllByName() method returns an array of InetAddresses that represent all of
the address that a particular host name.
import java.net.*; //required for InetAddress Class
public class Address{
public static void main(String[] args){
try {
InetAddress addressList[ ] = InetAddress.getAllByName(“wixnets.com”);
for(int i=0;i<addressList.length;i++){
System.out.println(addressList[i]);
}
}catch(UnknownHostException e) {
System.out.println(e);
}
}
}
Output
InetAddress.getLocalHost()
 The getLocalHost() method takes local host name and return InetAddress
 Which is IP address and name of your current system.
import java.net.*; //required for InetAddress Class
public class Address{
public static void main(String[] args){
try {
InetAddress localhost=InetAddress.getLocalHost();
System.out.println(“LocalHost: ”+ localhost);
}catch(UnknownHostException e) {
System.out.println(e);
}
}
}
Output
InetAddress: getHostName()
 The getHostName() method takes IP address and return host/ server name in string
format.
import java.net.*; //required for InetAddress Class
public class Address{
public static void main(String[] args){
try {
InetAddress ip = InetAddress.getByName(“10.254.3.79”);
System.out.println(“Hostname:”+ip.getHostName());
}catch(UnknownHostException e) {
System.out.println(e);
}
}
}
Output
InetAddress: getHostAddress()
 The getHostAddress() method takes host name (server name) and return IP address in
string format.
import java.net.*; //required for InetAddress Class
public class Address{
public static void main(String[] args){
try {
InetAddress ip = InetAddress.getByName(“www.vsitr.ac.in”);
System.out.println(“HostAddress: ”+ip.getHostAddress());
}catch(UnknownHostException e) {
System.out.println(e);
}
}
}
Output
Program
import java.net.*; //required for InetAddress Class
public class Address{
public static void main(String[] args){
try {
InetAddress ip = InetAddress.getByName(“www.vsitr.ac.in”);
System.out.println(“Host Name: ”+ip.getHostName());
System.out.println(“IP Address:”+ ip.getHostAddress());
}catch(UnknownHostException e) {
System.out.println(e);
}
}
}
Output
Write a program to accept a website name and return its IPAddress, after checking it on
Internet
URL
 Uniform Resource Locator
 URL provides an intelligible form to uniquely identify resources on the internet.
 URLs are universal, every browser uses them to identify resources on the web.
 URL Contains 4 components.
1. Protocol (http://)
2. Server name or IP address (www.darshan.ac.in)
3. Port number which is optional (:8090)
4. Directory resource (index.html)
http://10.255.1.1:8090/index.html
Port Number
Protocol
Server name or IP Address File Name or directory name
URL
 URL is represent by class URL in java.net package.
 Use following formats for creating a object of URL class
URL obj=new URL(String protocol, String host, int port, String path) throws
MalformedURLException
URL obj=new URL(String protocol, String host, String path) throws
MalformedURLException
OR
URL obj=new URL(String urlSpecifier) throws MalformedURLException
OR
URL class methods
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 getAuthority() it returns the authority part of the URL.
public String toString() it returns the string representation of the URL.
public String getQuery() it returns the query string of the URL.
public String getDefaultPort() it returns the default port of the URL.
public URLConnection openConnection() it returns the instance of URLConnection i.e. associated with this
URL.
public URI toURI() it returns a URI of the URL.
Program
import java.net.*; //required for InetAddress Class
public class URLDemo{
public static void main(String[] args){
try {
URL url=
new URL(“http://www.vsitr.ac.in/”);
System.out.println(“Protocol: “+url.getProtocol());
System.out.println(“Host : “+url.getHost());
System.out.println(“Port : “+url.getPort());
System.out.println(“File : “+url.getFile());
}catch(Exception e) {
System.out.println(e);
}
}
}
Output
Write a program to get the Protocol, Host Name, Port Number, and Default File Name from
given URL.
URLConnection
 URLConnection class is useful to actually connect to a website or resource on a network
and get all the details of the website.
 For example, to know the details of www.vsitr.ac.in, we should pass its URL to the object of
URL class.
 Then using openConnection() method, we should establish a connection with the site on
internet.
 openConnection() method returns URLConnection object.
URL obj=new URL(String urlSpecifier) throws MalformedURLException
URLConnection conn=obj.openConnection();
URLConnection class methods
Method Description
public int getContentLength() it returns the size in bytes of the content as a int.
public long getContentLengthLong() it returns the size in bytes of the content as a long.(Added by JDK 7)
public String getContentType() it returns the content-type of the resource.
public long getDate() it returns the time and date of the response in milliseconds.
public long getExpiration() it returns the expiration time and date of the resource.
public String getHeaderField(int index) it returns the value of specific index position.
public String getHeaderField(String
fieldName)
it returns the value of the header field whose name is specified by
field name.
public InputStream getInputStream() throws
IOException
Returns an input stream that reads from open connection.
public OutputStream getOutputStream()
throws IOException
Returns an output stream that writes into open connection.
Program
import java.net.*; //required for InetAddress Class
import java.io.*;
import java.util.*;
public class URLConnectionDemo{
public static void main(String[] args){
try {
URL url=new
URL(“https://www.w3schools.com/html/default.asp”);
URLConnection con = url.openConnection();
System.out.println(“Date: “ + new
Date(con.getDate()));
System.out.println(“Content-type: “ +
con.getContentType());
System.out.println(“Expiry: “ +
con.getExpiration());
System.out.println(“Length of content: “ +
con.getContentLength());
if(con.getContentLength()>0){
int ch;
InputStream in=con.getInputStream();
while ((ch=in.read())!=-1) {
System.out.print((char)ch);
}
}
}catch(MalformedURLException e) {
System.out.println(e);
Write a program to display the details and page contents of your website.
Date: Wed Jan 27 10:22:47 IST 2021
Content-type: text/html
Expiry: 1611737567000
Length of content: 62188
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HTML Tutorial</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-
width, initial-scale=1">
...
...
...
<![endif]-->
</body>
</html>
Output
Client – Server Architecture
 A Client-Server Architecture consists of two types of components: clients and servers.
 A server component is waiting for requests from client components.
 When a request is received, the server processes the request, and then send a response back to
the client.
Server Client
socket socket
Request
Response
Waits
Socket Overview
 “A socket is one endpoint of a two-way communication link between two programs running on
the network.”
 A Socket is combination of an IP address and a port number.
 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.
 There are two kinds of TCP sockets in java.
 One is for server, and other is for client.
 The Socket class is for clients, and ServerSocket class is for server.
Socket Overview
 The server is just like any ordinary program
running in a computer.
 Each computer is equipped with some ports.
 The server connects with port.
 This process is called binding to a port.
 The connection is called a server socket.
Computer
S
E
R
V
E
R
Computer where
server is running
Server Socket
ServerSocket ss = new ServerSocket(80)
The Java code for creating server in Network Programming:
1010
80
5566
1080
2010
3040
Port Number
Socket Overview
 Server is waiting for client machine to connect.
 Now, client come for communication with
server.
 In the next step the client connects to this port
of the server's computer.
 The connection is called a (client) socket.
 Now, connection is established between client
and server.
 Every time a client is found, its Socket is
extracted, and the loop again waits for the next
client.
Computer
S
E
R
V
E
R
Socket sock = new
Socket(“www.darshan.ac.in”,80);
The Java code for creating socket at client side.
1010
80
5566
1080
2010
3040
Socket
TCP/IP socket setup at Client & Server side
 At server side, create server socket with some port number using ServerSocket class of
java.net package.
ServerSocket ss=new ServerSocket(int port);
 Now, we should make the server wait till a client accepts connection, this is done using
accept() method.
 This object is used to establish communication with the clients
Socket s=ss.accept();
 At client side, create socket with host name and port number using Socket class.
 Use following formats for creating a object of Socket class.
Socket s=new Socket(String hostName, int port);
Socket s=new Socket(InetAddress ipAddress, int
port);
OR
Sockets class method
 Socket defines several instance method.
Method Description
public InetAddress getInetAddress() Returns the address of the Socket object.
public int getPort() Returns the remote port to which the invoking Socket object is
connected
public int getLocalPort() Returns the local port number.
public InputStream getInputStream()
throws IOException
Returns an input stream that reads(receive) data from this open
connection.
public OutputStream getOutputStream()
throws IOException
Returns an output stream that writes(send) data to open connection.
public void connect(SocketAddress
endpoint, int timeout)
Connects this socket to the server with a specified timeout value.
(I/O) package in Java
 In Java, streams are the sequence of data that are read from the source and written to the
destination.
 The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java.
 There are two type of Streams
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.
 PrintStream – it formats the primitive values as text
Server Client
Socket
ServerSocket
PrintStream BufferedReader
OutputStream InputStream
Creating a Server That Sends Data
 Create a server socket with port number
ServerSocket ss=new ServerSocket (8070);
 Waiting for establish a connection with client
Socket s=ss.accept();
 For sending a data attach output stream to the server socket using getOutputStream()
method.
OutputStream obj=s.getOutputStream();
 Create PrintStream object to send data into the socket
PrintStream ps=new PrintStream(obj);
 Call print() or println() method to send data.
ps.println(str);
 Close the connection.
ss.close(); //close ServerSocket
s.close(); //close Socket
ps.close(); // //close PrintStream
Creating a Client That Receiving Data
 Create a Socket object with server address and port number
Socket s=new Socket(“localhost”,8070);
 For receiving data attach input stream to the socket, using getInputStream() method
InputStream inStr=s.getInputStream();
 To read the data from socket, we can take the help of BufferedReader
BufferedReader br=new BufferedReader(new InputStreamReader(inStr));
 Reade data from BufferedReader object using read() or readLine() method.
String receivedMessage = br.readLine();
 Close the connection.
br.close(); //close BufferReader
s.close(); //close Socket
Program
import java.net.*;
import java.io.*;
public class MyServer{
public static void main(String[] args){
try {
ServerSocket ss = new ServerSocket(888);
Socket s = ss.accept();
OutputStream obj = s.getOutputStream();
PrintStream ps = new PrintStream(obj);
ps.println(“Hello client”);
ss.close(); //close ServerSocket
s.close(); //close Socket
ps.close(); //close Printstream
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Write a program to create server for the purpose of sending message to the client and also write client side program, which
accept all the strings sent by the server.
Message: Hello client
Output
import java.net.*;
import java.io.*;
public class MyClient {
public static void main(String[] args){
try {
Socket s=new Socket("localhost",888);
InputStream inStr=s.getInputStream();
BufferedReader br=new BufferedReader(new
InputStreamReader(inStr));
String receivedMessage = br.readLine();
System.out.println(“Message: “+receivedMessage);
br.close(); //close BufferReader
s.close(); //close Socket
} catch (IOException ex) {
ex.printStackTrace();
}
}}
Datagrams
 Datagrams are bundles of information passed between machines.
 A datagram is an independent, self-contained message sent over the network whose arrival,
arrival time, and content are not guaranteed.
 Once the datagram has been released to its intended target, there is no assurance that it will
arrive or even that someone will be there to catch it.
 When the datagram is received, there is no assurance that it hasn’t been damaged in transit or
that whoever sent it is still there to receive a response
 Java implements datagrams on top of the UDP (User Datagram Protocol) protocol by using two
classes:
 DatagramPacket object is the data container.
 DatagramSocket is the mechanism used to send or receive the DatagramPackets.
DatagramSocket
 DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets.
 Use following formats for creating a object of DatagramSocket class
DatagramSocket ds=new DatagramSocket() throws SocketException;
DatagramSocket ds=new DatagramSocket(int port) throws SocketException
DatagramSocket ds=new DatagramSocket(int port,InetAddress ipAddress) throws
SocketException
 it creates a datagram socket and binds it with the available Port Number on the localhost
machine.
 it creates a datagram socket and binds it with the given Port Number.
 it creates a datagram socket and binds it with the specified port number and host address.
DatagramSocket class method
 DatagramSocket defines several instance method.
Method Description
public InetAddress getInetAddress() If the socket is connected, then the address is returned.
public int getPort() Returns the number of the port to which the socket is connected.
public int getLocalPort() Returns the local port number.
public boolean isBound() Returns true if the socket is bound to an address.
public boolean isConnected() Returns true if the socket is connected to a server.
DatagramPacket
 Java DatagramPacket is a message that can be sent or received.
 If you send multiple packet, it may arrive in any order.
 Additionally, packet delivery is not guaranteed.
 Use following formats for creating a object of DatagramPacket class
DatagramPacket dp=new DatagramPacket(byte data[ ],int size)
DatagramPacket dp=new DatagramPacket(byte data[ ], int size, InetAddress
ipAddress, int port)
 it specifies a buffer that will receive data and the size of a packet.
 It is used for receiving data over a DatagramSocket
 It’s transmits packets beginning at the specifies a target address and port, which are used by a
DatagramSocket to determine where the data in the packet will be sent.
Sending DatagramPacket by DatagramSocket
 Create a DatagramSocket object.
DatagramSocket ds=new DatagramSocket ();
 Create a InetAddress object with reciver’s ip address
InetAddress ip = InetAddress.getByName(“Reciver Address”);
 For sending a data create DatagramPacket object and pass the data within constructure,
 Also specify the size of data, address of receiver with port number
DatagramPacket dp=new DatagramPacket(byte data[ ], int size, InetAddress
ipAddress, int port)
 Call send() method of DatagramSocket and pass DatagramPacket into method.
ds.send(dp);
 Close the connection.
ds.close(); //close DatagramSocket
Receiving DatagramPacket by DatagramSocket
 Create a Datagram Socket object with specific port number.
DatagramSocket ds=new DatagramSocket (int port);
 Create a byte array for store a receive data, working like a buffer
byte[] buffer = new byte[1024];
 For receiving a data create Datagram Packet object and pass buffer and buffer size in
constructor
DatagramPacket dp=new DatagramPacket(buffer,1024)
 Call receive() method of DatagramSocket and pass DatagramPacket into method.
ds.receive(dp);
 Close the connection.
ds.close(); //close DatagramSocket
 Call getData() method of DatagramPacket for reading data.
String str =new String(dp.getData(),0,dp.getLength());
Program
import java.net.*;
import java.io.*;
public class UDPReceiver {
public static void main(String[] args) {
try {
DatagramSocket ds = new
DatagramSocket(6666);
byte buffer[] = new byte[1024];
DatagramPacket dp = new
DatagramPacket(buffer, 1024);
ds.receive(dp);
String str =new
String(dp.getData(),0,dp.getLength());
System.out.println("Receive: "+str);
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Write a program to create Sender and Receiver for connectionless communication.
Message: Message from Sender
Output
import java.net.*;
import java.io.*;
public class UDPSender {
public static void main(String[] args) {
try {
DatagramSocket ds=new
DatagramSocket();
String str="Message from Sender";
InetAddress ip=InetAddress.getByName("localhost");
DatagramPacket dp=new
DatagramPacket(str.getBytes(), str.length(), ip,
6666);
ds.send(dp);
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Java EE
 The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is
currently known as Jakarta EE.
 It is a set of specifications wrapping around Java SE (Standard Edition).
 The Java EE provides a platform for developers with enterprise features such as web services.
 Java EE applications are usually run on reference run times such as application servers.
 Examples of some contexts where Java EE is used are e-commerce, accounting, banking
information systems.
Specifications of Java EE
 Java EE has several specifications which are useful in making web pages, reading and writing
from database.
 The Java EE contains several APIs which have the functionalities of base Java SE APIs such as
Enterprise JavaBeans, connectors, Servlets, Java Server Pages and several web service
technologies.
 Web Specifications of Java EE
 Web Service Specifications of Java EE
 Enterprise Specifications of Java EE
 Other Specifications of Java EE
Web Specifications of Java EE
 Servlet- This specification defines how you can manage HTTP requests either in a synchronous
or asynchronous way. It is low level, and other specifications depend on it
 Web Socket- Web Socket is a computer communication protocol, and this API provides a set of
APIs to facilitate Web Socket connections.
 Java Server Faces- It is a service which helps in building GUI out of components.
 Unified Expression Language- It is a simple language which was designed to facilitate web
application developers.

More Related Content

Similar to CHAPTER - 3 - JAVA NETWORKING.pptx

Javanetworkingbasicssocketsoverview
JavanetworkingbasicssocketsoverviewJavanetworkingbasicssocketsoverview
Javanetworkingbasicssocketsoverviewrajshreemuthiah
 
Java networking basics & sockets overview
Java networking basics & sockets overviewJava networking basics & sockets overview
Java networking basics & sockets overviewrajshreemuthiah
 
Networking
NetworkingNetworking
NetworkingTuan Ngo
 
Unit8 java
Unit8 javaUnit8 java
Unit8 javamrecedu
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programmingashok hirpara
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelChapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelCSDeptSriKaliswariCo
 
Module 1 networking basics-2
Module 1   networking basics-2Module 1   networking basics-2
Module 1 networking basics-2Ankit Dubey
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programmingAnung Ariwibowo
 
Java API: java.net.InetAddress
Java API: java.net.InetAddressJava API: java.net.InetAddress
Java API: java.net.InetAddressSayak Sarkar
 
Android networking in Hindi
Android networking in Hindi Android networking in Hindi
Android networking in Hindi Vipin sharma
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 

Similar to CHAPTER - 3 - JAVA NETWORKING.pptx (20)

Advance Java
Advance JavaAdvance Java
Advance Java
 
Lecture6
Lecture6Lecture6
Lecture6
 
Javanetworkingbasicssocketsoverview
JavanetworkingbasicssocketsoverviewJavanetworkingbasicssocketsoverview
Javanetworkingbasicssocketsoverview
 
Java networking basics & sockets overview
Java networking basics & sockets overviewJava networking basics & sockets overview
Java networking basics & sockets overview
 
Networking
NetworkingNetworking
Networking
 
Lecture10
Lecture10Lecture10
Lecture10
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
Unit8 java
Unit8 javaUnit8 java
Unit8 java
 
URL Class in JAVA
URL Class in JAVAURL Class in JAVA
URL Class in JAVA
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Java 1
Java 1Java 1
Java 1
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelChapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & Deitel
 
Module 1 networking basics-2
Module 1   networking basics-2Module 1   networking basics-2
Module 1 networking basics-2
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
Java API: java.net.InetAddress
Java API: java.net.InetAddressJava API: java.net.InetAddress
Java API: java.net.InetAddress
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Android networking in Hindi
Android networking in Hindi Android networking in Hindi
Android networking in Hindi
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 

Recently uploaded

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

CHAPTER - 3 - JAVA NETWORKING.pptx

  • 1. mjpatel.cse@vsitr.ac.in Computer Science Engineering Department Unit-3 : Java Networking Vidush Somany institute of Technology & Research, Kadi Kadi Sarva Vishwavidyalaya , Gandhinagar
  • 2.  Looping Outline  Network Basics  Networking Terminology  InetAddress  URL  URLConnection  Client/Server architecture  Socket overview  TCP/IP client sockets  TCP/IP server sockets  Datagrams  DatagramsSocket  DatagramsPacket
  • 3. Network Basics  Represent interconnection of computing devices either by using cable or wireless devices for resources sharing.  In network, there may be several computers, some of them receiving the services and some providing services to other.  The computer which receives service is called a client.  The computer which provides the service is called server. A Network is
  • 4. Networking Terminology  IP Address : A unique identification number allotted to every device on a network.  DNS (Domain Name Service) : A service on internet that maps the IP addresses with corresponding website names.  Port Number : 2 byte unique identification number for socket.  URL (Uniform Resource Locator): Global address of document and other resources on the world wide web.  TCP/IP: Connection oriented reliable protocol, highly suitable for transporting data reliably on a network.  UDP: Transfers data in a connection less and unreliable manner
  • 5. Network Programming  The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.  java.net package provides many classes to deal with networking applications in Java  Here there are few classes related to the connection and then identifying a connection  InetAddress  URL  URLConnection  For making a actually communication (sending and receiving data) deal with few more classes like ,  Socket  ServerSocket  DatagramPacket  DatagramSocket
  • 6. InetAddress  InetAddress class belong to the java.net package.  Using InetAddress class, it is possible to know the IP Address of website / host name  InetAddress class is used to encapsulate both the numerical IP address and host name for the address. Commonly used methods of InetAddress class Method Description public static InetAddress getByName(String host) throws UnknownHostException Determines the IP address of a given host's name. public static InetAddress getAllByName (String host) throws UnknownHostException It returns an array of IP Addresses that a particular host name. public static InetAddress getLocalHost() throws UnknownHostException Returns the address of the local host. public String getHostName() it returns the host name of the IP address. public String getHostAddress() it returns the IP address in string format.
  • 7. InetAddress.getByName()  The getByName() method takes host name (server name) and return InetAddress  Which is nothing but the IP address of the server. import java.net.*; //required for InetAddress Class public class Address{ public static void main(String[] args){ try { InetAddress ip = InetAddress.getByName(“www.vsitr.ac.in”); System.out.println("IP: "+ip); }catch(UnknownHostException e) { System.out.println(e); } } } Output
  • 8. InetAddress.getAllByName()  The getAllByName() method returns an array of InetAddresses that represent all of the address that a particular host name. import java.net.*; //required for InetAddress Class public class Address{ public static void main(String[] args){ try { InetAddress addressList[ ] = InetAddress.getAllByName(“wixnets.com”); for(int i=0;i<addressList.length;i++){ System.out.println(addressList[i]); } }catch(UnknownHostException e) { System.out.println(e); } } } Output
  • 9. InetAddress.getLocalHost()  The getLocalHost() method takes local host name and return InetAddress  Which is IP address and name of your current system. import java.net.*; //required for InetAddress Class public class Address{ public static void main(String[] args){ try { InetAddress localhost=InetAddress.getLocalHost(); System.out.println(“LocalHost: ”+ localhost); }catch(UnknownHostException e) { System.out.println(e); } } } Output
  • 10. InetAddress: getHostName()  The getHostName() method takes IP address and return host/ server name in string format. import java.net.*; //required for InetAddress Class public class Address{ public static void main(String[] args){ try { InetAddress ip = InetAddress.getByName(“10.254.3.79”); System.out.println(“Hostname:”+ip.getHostName()); }catch(UnknownHostException e) { System.out.println(e); } } } Output
  • 11. InetAddress: getHostAddress()  The getHostAddress() method takes host name (server name) and return IP address in string format. import java.net.*; //required for InetAddress Class public class Address{ public static void main(String[] args){ try { InetAddress ip = InetAddress.getByName(“www.vsitr.ac.in”); System.out.println(“HostAddress: ”+ip.getHostAddress()); }catch(UnknownHostException e) { System.out.println(e); } } } Output
  • 12. Program import java.net.*; //required for InetAddress Class public class Address{ public static void main(String[] args){ try { InetAddress ip = InetAddress.getByName(“www.vsitr.ac.in”); System.out.println(“Host Name: ”+ip.getHostName()); System.out.println(“IP Address:”+ ip.getHostAddress()); }catch(UnknownHostException e) { System.out.println(e); } } } Output Write a program to accept a website name and return its IPAddress, after checking it on Internet
  • 13. URL  Uniform Resource Locator  URL provides an intelligible form to uniquely identify resources on the internet.  URLs are universal, every browser uses them to identify resources on the web.  URL Contains 4 components. 1. Protocol (http://) 2. Server name or IP address (www.darshan.ac.in) 3. Port number which is optional (:8090) 4. Directory resource (index.html) http://10.255.1.1:8090/index.html Port Number Protocol Server name or IP Address File Name or directory name
  • 14. URL  URL is represent by class URL in java.net package.  Use following formats for creating a object of URL class URL obj=new URL(String protocol, String host, int port, String path) throws MalformedURLException URL obj=new URL(String protocol, String host, String path) throws MalformedURLException OR URL obj=new URL(String urlSpecifier) throws MalformedURLException OR
  • 15. URL class methods 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 getAuthority() it returns the authority part of the URL. public String toString() it returns the string representation of the URL. public String getQuery() it returns the query string of the URL. public String getDefaultPort() it returns the default port of the URL. public URLConnection openConnection() it returns the instance of URLConnection i.e. associated with this URL. public URI toURI() it returns a URI of the URL.
  • 16. Program import java.net.*; //required for InetAddress Class public class URLDemo{ public static void main(String[] args){ try { URL url= new URL(“http://www.vsitr.ac.in/”); System.out.println(“Protocol: “+url.getProtocol()); System.out.println(“Host : “+url.getHost()); System.out.println(“Port : “+url.getPort()); System.out.println(“File : “+url.getFile()); }catch(Exception e) { System.out.println(e); } } } Output Write a program to get the Protocol, Host Name, Port Number, and Default File Name from given URL.
  • 17. URLConnection  URLConnection class is useful to actually connect to a website or resource on a network and get all the details of the website.  For example, to know the details of www.vsitr.ac.in, we should pass its URL to the object of URL class.  Then using openConnection() method, we should establish a connection with the site on internet.  openConnection() method returns URLConnection object. URL obj=new URL(String urlSpecifier) throws MalformedURLException URLConnection conn=obj.openConnection();
  • 18. URLConnection class methods Method Description public int getContentLength() it returns the size in bytes of the content as a int. public long getContentLengthLong() it returns the size in bytes of the content as a long.(Added by JDK 7) public String getContentType() it returns the content-type of the resource. public long getDate() it returns the time and date of the response in milliseconds. public long getExpiration() it returns the expiration time and date of the resource. public String getHeaderField(int index) it returns the value of specific index position. public String getHeaderField(String fieldName) it returns the value of the header field whose name is specified by field name. public InputStream getInputStream() throws IOException Returns an input stream that reads from open connection. public OutputStream getOutputStream() throws IOException Returns an output stream that writes into open connection.
  • 19. Program import java.net.*; //required for InetAddress Class import java.io.*; import java.util.*; public class URLConnectionDemo{ public static void main(String[] args){ try { URL url=new URL(“https://www.w3schools.com/html/default.asp”); URLConnection con = url.openConnection(); System.out.println(“Date: “ + new Date(con.getDate())); System.out.println(“Content-type: “ + con.getContentType()); System.out.println(“Expiry: “ + con.getExpiration()); System.out.println(“Length of content: “ + con.getContentLength()); if(con.getContentLength()>0){ int ch; InputStream in=con.getInputStream(); while ((ch=in.read())!=-1) { System.out.print((char)ch); } } }catch(MalformedURLException e) { System.out.println(e); Write a program to display the details and page contents of your website. Date: Wed Jan 27 10:22:47 IST 2021 Content-type: text/html Expiry: 1611737567000 Length of content: 62188 <!DOCTYPE html> <html lang="en-US"> <head> <title>HTML Tutorial</title> <meta charset="utf-8"> <meta name="viewport" content="width=device- width, initial-scale=1"> ... ... ... <![endif]--> </body> </html> Output
  • 20. Client – Server Architecture  A Client-Server Architecture consists of two types of components: clients and servers.  A server component is waiting for requests from client components.  When a request is received, the server processes the request, and then send a response back to the client. Server Client socket socket Request Response Waits
  • 21. Socket Overview  “A socket is one endpoint of a two-way communication link between two programs running on the network.”  A Socket is combination of an IP address and a port number.  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.  There are two kinds of TCP sockets in java.  One is for server, and other is for client.  The Socket class is for clients, and ServerSocket class is for server.
  • 22. Socket Overview  The server is just like any ordinary program running in a computer.  Each computer is equipped with some ports.  The server connects with port.  This process is called binding to a port.  The connection is called a server socket. Computer S E R V E R Computer where server is running Server Socket ServerSocket ss = new ServerSocket(80) The Java code for creating server in Network Programming: 1010 80 5566 1080 2010 3040 Port Number
  • 23. Socket Overview  Server is waiting for client machine to connect.  Now, client come for communication with server.  In the next step the client connects to this port of the server's computer.  The connection is called a (client) socket.  Now, connection is established between client and server.  Every time a client is found, its Socket is extracted, and the loop again waits for the next client. Computer S E R V E R Socket sock = new Socket(“www.darshan.ac.in”,80); The Java code for creating socket at client side. 1010 80 5566 1080 2010 3040 Socket
  • 24. TCP/IP socket setup at Client & Server side  At server side, create server socket with some port number using ServerSocket class of java.net package. ServerSocket ss=new ServerSocket(int port);  Now, we should make the server wait till a client accepts connection, this is done using accept() method.  This object is used to establish communication with the clients Socket s=ss.accept();  At client side, create socket with host name and port number using Socket class.  Use following formats for creating a object of Socket class. Socket s=new Socket(String hostName, int port); Socket s=new Socket(InetAddress ipAddress, int port); OR
  • 25. Sockets class method  Socket defines several instance method. Method Description public InetAddress getInetAddress() Returns the address of the Socket object. public int getPort() Returns the remote port to which the invoking Socket object is connected public int getLocalPort() Returns the local port number. public InputStream getInputStream() throws IOException Returns an input stream that reads(receive) data from this open connection. public OutputStream getOutputStream() throws IOException Returns an output stream that writes(send) data to open connection. public void connect(SocketAddress endpoint, int timeout) Connects this socket to the server with a specified timeout value.
  • 26. (I/O) package in Java  In Java, streams are the sequence of data that are read from the source and written to the destination.  The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java.  There are two type of Streams  InPutStream − The InputStream is used to read data from a source.  OutPutStream − The OutputStream is used for writing data to a destination.  PrintStream – it formats the primitive values as text Server Client Socket ServerSocket PrintStream BufferedReader OutputStream InputStream
  • 27. Creating a Server That Sends Data  Create a server socket with port number ServerSocket ss=new ServerSocket (8070);  Waiting for establish a connection with client Socket s=ss.accept();  For sending a data attach output stream to the server socket using getOutputStream() method. OutputStream obj=s.getOutputStream();  Create PrintStream object to send data into the socket PrintStream ps=new PrintStream(obj);  Call print() or println() method to send data. ps.println(str);  Close the connection. ss.close(); //close ServerSocket s.close(); //close Socket ps.close(); // //close PrintStream
  • 28. Creating a Client That Receiving Data  Create a Socket object with server address and port number Socket s=new Socket(“localhost”,8070);  For receiving data attach input stream to the socket, using getInputStream() method InputStream inStr=s.getInputStream();  To read the data from socket, we can take the help of BufferedReader BufferedReader br=new BufferedReader(new InputStreamReader(inStr));  Reade data from BufferedReader object using read() or readLine() method. String receivedMessage = br.readLine();  Close the connection. br.close(); //close BufferReader s.close(); //close Socket
  • 29. Program import java.net.*; import java.io.*; public class MyServer{ public static void main(String[] args){ try { ServerSocket ss = new ServerSocket(888); Socket s = ss.accept(); OutputStream obj = s.getOutputStream(); PrintStream ps = new PrintStream(obj); ps.println(“Hello client”); ss.close(); //close ServerSocket s.close(); //close Socket ps.close(); //close Printstream } catch (IOException ex) { ex.printStackTrace(); } } } Write a program to create server for the purpose of sending message to the client and also write client side program, which accept all the strings sent by the server. Message: Hello client Output import java.net.*; import java.io.*; public class MyClient { public static void main(String[] args){ try { Socket s=new Socket("localhost",888); InputStream inStr=s.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(inStr)); String receivedMessage = br.readLine(); System.out.println(“Message: “+receivedMessage); br.close(); //close BufferReader s.close(); //close Socket } catch (IOException ex) { ex.printStackTrace(); } }}
  • 30. Datagrams  Datagrams are bundles of information passed between machines.  A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.  Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it.  When the datagram is received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a response  Java implements datagrams on top of the UDP (User Datagram Protocol) protocol by using two classes:  DatagramPacket object is the data container.  DatagramSocket is the mechanism used to send or receive the DatagramPackets.
  • 31. DatagramSocket  DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.  Use following formats for creating a object of DatagramSocket class DatagramSocket ds=new DatagramSocket() throws SocketException; DatagramSocket ds=new DatagramSocket(int port) throws SocketException DatagramSocket ds=new DatagramSocket(int port,InetAddress ipAddress) throws SocketException  it creates a datagram socket and binds it with the available Port Number on the localhost machine.  it creates a datagram socket and binds it with the given Port Number.  it creates a datagram socket and binds it with the specified port number and host address.
  • 32. DatagramSocket class method  DatagramSocket defines several instance method. Method Description public InetAddress getInetAddress() If the socket is connected, then the address is returned. public int getPort() Returns the number of the port to which the socket is connected. public int getLocalPort() Returns the local port number. public boolean isBound() Returns true if the socket is bound to an address. public boolean isConnected() Returns true if the socket is connected to a server.
  • 33. DatagramPacket  Java DatagramPacket is a message that can be sent or received.  If you send multiple packet, it may arrive in any order.  Additionally, packet delivery is not guaranteed.  Use following formats for creating a object of DatagramPacket class DatagramPacket dp=new DatagramPacket(byte data[ ],int size) DatagramPacket dp=new DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)  it specifies a buffer that will receive data and the size of a packet.  It is used for receiving data over a DatagramSocket  It’s transmits packets beginning at the specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent.
  • 34. Sending DatagramPacket by DatagramSocket  Create a DatagramSocket object. DatagramSocket ds=new DatagramSocket ();  Create a InetAddress object with reciver’s ip address InetAddress ip = InetAddress.getByName(“Reciver Address”);  For sending a data create DatagramPacket object and pass the data within constructure,  Also specify the size of data, address of receiver with port number DatagramPacket dp=new DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)  Call send() method of DatagramSocket and pass DatagramPacket into method. ds.send(dp);  Close the connection. ds.close(); //close DatagramSocket
  • 35. Receiving DatagramPacket by DatagramSocket  Create a Datagram Socket object with specific port number. DatagramSocket ds=new DatagramSocket (int port);  Create a byte array for store a receive data, working like a buffer byte[] buffer = new byte[1024];  For receiving a data create Datagram Packet object and pass buffer and buffer size in constructor DatagramPacket dp=new DatagramPacket(buffer,1024)  Call receive() method of DatagramSocket and pass DatagramPacket into method. ds.receive(dp);  Close the connection. ds.close(); //close DatagramSocket  Call getData() method of DatagramPacket for reading data. String str =new String(dp.getData(),0,dp.getLength());
  • 36. Program import java.net.*; import java.io.*; public class UDPReceiver { public static void main(String[] args) { try { DatagramSocket ds = new DatagramSocket(6666); byte buffer[] = new byte[1024]; DatagramPacket dp = new DatagramPacket(buffer, 1024); ds.receive(dp); String str =new String(dp.getData(),0,dp.getLength()); System.out.println("Receive: "+str); ds.close(); } catch (Exception ex) { ex.printStackTrace(); } } } Write a program to create Sender and Receiver for connectionless communication. Message: Message from Sender Output import java.net.*; import java.io.*; public class UDPSender { public static void main(String[] args) { try { DatagramSocket ds=new DatagramSocket(); String str="Message from Sender"; InetAddress ip=InetAddress.getByName("localhost"); DatagramPacket dp=new DatagramPacket(str.getBytes(), str.length(), ip, 6666); ds.send(dp); ds.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
  • 37. Java EE  The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is currently known as Jakarta EE.  It is a set of specifications wrapping around Java SE (Standard Edition).  The Java EE provides a platform for developers with enterprise features such as web services.  Java EE applications are usually run on reference run times such as application servers.  Examples of some contexts where Java EE is used are e-commerce, accounting, banking information systems.
  • 38. Specifications of Java EE  Java EE has several specifications which are useful in making web pages, reading and writing from database.  The Java EE contains several APIs which have the functionalities of base Java SE APIs such as Enterprise JavaBeans, connectors, Servlets, Java Server Pages and several web service technologies.  Web Specifications of Java EE  Web Service Specifications of Java EE  Enterprise Specifications of Java EE  Other Specifications of Java EE
  • 39. Web Specifications of Java EE  Servlet- This specification defines how you can manage HTTP requests either in a synchronous or asynchronous way. It is low level, and other specifications depend on it  Web Socket- Web Socket is a computer communication protocol, and this API provides a set of APIs to facilitate Web Socket connections.  Java Server Faces- It is a service which helps in building GUI out of components.  Unified Expression Language- It is a simple language which was designed to facilitate web application developers.