SlideShare a Scribd company logo
 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
 interconnection of computing devices for resources sharing.
 The computer which receives service is called a client.
 The computer which provides the service is called server.
 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/resources on the world wide
web.
 TCP/IP: Connection oriented , reliable protocol
 UDP: connection less , unreliable
A Network is
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 for networking applications in Java
 classes related to the connection and then identifying a connection

 For making a actually communication (sending and receiving data)

Java.net Package
InetAddress : Internet Protocol (IP) address
URL : Uniform Resource Locator, a pointer to a "resource" on the World Wide Web.
URLConnection : Represent the communications link between the application and a URL
ServerSocket : create a server socket, establish communication with the clients.
Socket :implements client sockets
DatagramPacket : represents a datagram packet.
DatagramSocket : socket for sending and receiving datagram packets.
InetAddress

 Use to get the IP Address of website / host name
 used to encapsulate both the numerical IP address and host name.
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 has.
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.
String toString() Converts this IP address to a String.
boolean equals(Object obj) Compares this object against the specified object.
static InetAddress getLoopbackAddress() Returns the loopback address. (localhost, address of itself)
import java.net.*;
public class Address {
public static void main(String[] args) {
try {
// Using getByName() to get IP address from host name
InetAddress ip = InetAddress.getByName("www.darshan.ac.in");
System.out.println("IP: " + ip);
// Using getAllByName() to get an array of IP addresses from host name
InetAddress addressList[] = InetAddress.getAllByName("wixnets.com");
for (int i = 0; i < addressList.length; i++) {
System.out.println(addressList[i]); }
// Using getLocalHost() to get the IP address and name of the local host
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("LocalHost: " + localhost);
// Using getHostName() to get host/server name from IP address
InetAddress ip2 = InetAddress.getByName("10.254.3.79");
System.out.println("Hostname: " + ip2.getHostName());
// Using getHostAddress() to get IP address from host name
InetAddress ip3 = InetAddress.getByName("www.darshan.ac.in");
System.out.println("HostAddress: " + ip3.getHostAddress());
} catch (UnknownHostException e) { System.out.println(e);
} } }
IP: www.darshan.ac.in/89.238.188.50
wixnets.com/104.18.48.113
wixnets.com/172.67.198.137
wixnets.com/104.18.49.113
LocalHost: LAPTOP-NB4I63VB/10.254.3.79
Hostname: LAPTOP-NB4I63VB
HostAddress: 89.238.188.50
Program
Write a program to accept a website name and return its IPAddress, after checking it on
Internet
URL
 Uniform Resource Locator
 uniquely identify resources on the internet.
 pointer to “resource” on the World Wide Web.
Get info about URL
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)
URL url=new URL("http://www.darshan.ac.in");
URLConnection urlcon=url.openConnection();
http://www.example.com:8090/path/index.html?key1=value1&key2=value2
Port Number
Protocol
Server name or IP Address
(Domain name) parameter
Path to fie
OR
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( host name + port) part of the URL.
public String toString() it returns the string representation of the URL.
public String getQuery() it returns the query string( variable + value pair) of the URL.
public String getDefaultPort() it returns the default port of the URL.
public URLConnection openConnection() used to establish a URL connection to the specified URL
public URI toURI() it returns a URI (uniform recourse identifier) of the URL.
URI class is useful when you need to perform more generic
operations on a Uniform Resource Identifier.
Program
Write a program to get the Protocol, Host Name, Port Number, and Default File Name from
given URL.
URLConnection
 class is useful to actually connect to a website / resource on a network and
get all the details about content
 - establish a connection with the site on internet.
 returns object.
URL obj=new URL(String urlSpecifier) throws MalformedURLException
URLConnection conn=obj.openConnection();
URL url=new URL("http://www.darshan.ac.in");
URLConnection urlcon=url.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) retrieve the value of a header field at the specified index.
public String getHeaderField(String
fieldName)
it returns the value of the header field specified by field name.
public InputStream getInputStream() throws
IOException
Returns an input stream that reads from this open connection.
public OutputStream getOutputStream()
throws IOException
Returns an output stream that writes into this open connection.
Program Write a program to display the details and page contents of your website.
Client – Server Architecture
 Two machines must connect
 Server waits for connection
 Client initiates connection
 Server responds to the client request
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.
 The Socket class is for clients, and ServerSocket class is for server.
Socket Overview
 Server has many ports, server program connects
to one of these ports, a process known as
"binding to a port." This connection is
established through a server socket.
 Server is waiting for client machine to connect.
 When a client wants to communicate with the
server, it connects to the server's port. This
connection is established through a client
socket.
 Every time a client connects, its socket is
extracted.
 The server loop then waits for the next client.
Computer
S
E
R
V
E
R
Computer where
server is running
Server Socket
The Java code for creating server in Network Programming:
1010
80
5566
1080
2010
3040
Port Number
The Java code for creating socket at client side.
Socket
TCP/IP socket setup at Client & Server side
 At server side, create server socket with some port number using class of
. package. Here port number, tells which service of server.
 server wait till a client accepts connection, this is done using method.(Accept client
request)
 used to establish communication with the clients
 At client side, create socket with host name and port number using class.
ip - which server , port - which service
OR
Sockets class method
 getInetAddress(): Returns the address of the Socket object.
 getPort(): Returns the remote port to which the Socket object is connected.
 getLocalPort(): Returns the local port number.
 getInputStream(): Returns an input stream that reads data from this open connection.
 getOutputStream(): Returns an output stream that writes data to the open connection.
 connect(SocketAddress endpoint, int timeout): Connects the socket to the specified endpoint
with a timeout.
(I/O) package in Java
 streams are the sequence of data
 The java.io package contains classes to perform input and output (I/O) in Java.
 There are two type of Streams
 − The InputStream is used to read data from a source.
 − The OutputStream is used for writing data to a destination.
 – it formats the string
import java.net.*;
import java.io.*;
public class MyServer {
public static void main(String[] args) {
try {
// Create a server socket that listens on port 888
ServerSocket ss = new ServerSocket(888);
// Wait for a client to connect and accept the connection
Socket s = ss.accept();
// For sending a data attach output stream to the server socket using method.
OutputStream obj = s.getOutputStream(); //write data
// Create a PrintStream to write text data to the output stream
PrintStream ps = new PrintStream(obj); //format data
// Send the message "Hello client" to the client
ps.println("Hello client");
ss.close(); // Close ServerSocket
s.close(); // Close Socket
ps.close(); // Close Printstream
} catch (IOException ex) {
// Print any exceptions that occur during execution
ex.printStackTrace();
}
}
}
This line blocks the server's execution until a client attempts to
connect to the server.
When a client connection request is received, the accept()
method returns a new Socket object.
Creating a Server That Sends Data
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.
import java.net.*;
import java.io.*;
public class MyClient {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 888); // Connect to server on localhost at port 888, here server in on local computer so
InputStream inStr = s.getInputStream(); //read data // For receiving data, attach input stream to the socket, using
method
BufferedReader br = new BufferedReader(new InputStreamReader(inStr)); // Create BufferedReader to read text data
String receivedMessage = br.readLine(); // Read message from BufferedReader using read() & readline()
System.out.println("Message: " + receivedMessage); // Print received message
br.close(); // Close BufferedReader
s.close(); // Close Socket
} catch (IOException ex) {
ex.printStackTrace(); // Print any exceptions that occur
}
}
}
Creating a Client That Receive Data
Datagrams
 datagrams are independent messages sent over a network, with no guarantee of arrival, arrival time.
 If you send multiple packet, it may arrive in any order, packet delivery is not guaranteed.
 Java implements datagrams using the UDP (User Datagram Protocol) protocol through two main classes:
 DatagramPacket: container for the data being transmitted. It encapsulates the data along with
information about its destination.
 DatagramSocket: used to send or receive DatagramPackets.
DatagramSocket:
 represents a connection-less socket used for sending and receiving datagram packets.
 DatagramSocket ds = new DatagramSocket();
 creates a datagram socket and binds it with an available port number on the localhost machine.
 DatagramSocket ds = new DatagramSocket(int port);
 creates a datagram socket and binds it with the given port number.
 DatagramSocket ds = new DatagramSocket(int port, InetAddress ipAddress);
 creates a datagram socket and binds it with the specified port number and host address.
DatagramSocket class methods:
 getInetAddress(): Returns the address to which the socket is connected.
 getPort(): Returns the port number to which the socket is connected.
 getLocalPort(): Returns the local port number.
 isBound(): Returns true if the socket is bound to an address.
 isConnected(): Returns true if the socket is connected to a server.
DatagramPacket class
 DatagramPacket dp = new DatagramPacket(byte data[], int size): buffer that will receive data and the size of a
packet.
 DatagramPacket dp = new DatagramPacket(byte data[], int offset, int size): specify an offset into the buffer
at which data will be stored
 DatagramPacket dp = new DatagramPacket(byte data[], int size, InetAddress ipAddress, int port): specified
target address and port, which are used by a DatagramSocket to determine where the data in the packet
will be sent.
import java.net.*;
public class UDPSender {
public static void main(String[] args) {
try {
// Create a DatagramSocket
DatagramSocket ds = new DatagramSocket();
// Create a message to send
String str = "Message from Sender";
// Get the IP address of the localhost (reciver’s ip address)
InetAddress ip = InetAddress.getByName("localhost");
// Create a DatagramPacket with the message, IP address, and port number
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 6666);
// Send the packet
ds.send(dp);
// Close the socket
ds.close();
} catch (Exception ex) {
// Print any exceptions that occur
ex.printStackTrace();
}
}
}
Sending DatagramPacket by DatagramSocket
Write a program to create Sender and Receiver for connectionless communication.
import java.net.*;
import java.io.*;
public class UDPReceiver {
public static void main(String[] args) {
try {
// Create a Datagram Socket object with specific port number.
DatagramSocket ds = new DatagramSocket(6666);
// Create a buffer to store received data
byte buffer[] = new byte[1024];
// Create a DatagramPacket to receive data into the buffer
DatagramPacket dp = new DatagramPacket(buffer, 1024);
// Receive data into the DatagramPacket
ds.receive(dp);
// Convert the received data into a String
String str = new String(dp.getData(), 0, dp.getLength());
// Print the received message
System.out.println("Received: " + str);
// Close the DatagramSocket
ds.close();
} catch (Exception ex) {
// Print any exceptions that occur
ex.printStackTrace();
} } }
Receiving DatagramPacket by DatagramSocket
1. Explain the usage of Socket class with example.
2. Implement the client server program using UDP Sockets. Client will request to download
the file from server and server will send it to client.
3. Compare ServerSocket with Socket(2)
4. How do you get the IP address of a machine from its hostname?
InetAddress ip = InetAddress.getByName("www.darshan.ac.in");
5. What are the differences between a TCP socket and UDP socket? How are they created in
Java?

More Related Content

Similar to Advanced Java Programming: Introduction and Overview of Java Networking 1. Introduction to Advanced Java Programming (20)

Networking in Java
Networking in JavaNetworking in Java
Networking in Java
Gaurav Agarwal
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
Sasi Kala
 
Networking
NetworkingNetworking
Networking
Jafar Nesargi
 
Java networking
Java networkingJava networking
Java networking
ssuser3a47cb
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
EliasPetros
 
Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptx
Esubesisay
 
T2
T2T2
T2
Mo Ch
 
28 networking
28  networking28  networking
28 networking
Ravindra Rathore
 
Socket
SocketSocket
Socket
Amandeep Kaur
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
arnold 7490
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
ashok hirpara
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
Tushar B Kute
 
Unit-6-java basic for java programing.pptx
Unit-6-java basic for java programing.pptxUnit-6-java basic for java programing.pptx
Unit-6-java basic for java programing.pptx
086ChintanPatel1
 
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
vasishtharishi07
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
Rakesh Madugula
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
phanleson
 
Networking slide
Networking slideNetworking slide
Networking slide
Asaduzzaman Kanok
 
Networking
NetworkingNetworking
Networking
Tuan Ngo
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
Sasi Kala
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
EliasPetros
 
Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptx
Esubesisay
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
ashok hirpara
 
Unit-6-java basic for java programing.pptx
Unit-6-java basic for java programing.pptxUnit-6-java basic for java programing.pptx
Unit-6-java basic for java programing.pptx
086ChintanPatel1
 
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
vasishtharishi07
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
phanleson
 
Networking
NetworkingNetworking
Networking
Tuan Ngo
 

Recently uploaded (20)

apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays
 
apidays New York 2025 - Unifying OpenAPI & AsyncAPI by Naresh Jain & Hari Kri...
apidays New York 2025 - Unifying OpenAPI & AsyncAPI by Naresh Jain & Hari Kri...apidays New York 2025 - Unifying OpenAPI & AsyncAPI by Naresh Jain & Hari Kri...
apidays New York 2025 - Unifying OpenAPI & AsyncAPI by Naresh Jain & Hari Kri...
apidays
 
SAP_S4HANA_EWM_Food_Processing_Industry.pptx
SAP_S4HANA_EWM_Food_Processing_Industry.pptxSAP_S4HANA_EWM_Food_Processing_Industry.pptx
SAP_S4HANA_EWM_Food_Processing_Industry.pptx
vemulavenu484
 
apidays New York 2025 - Lessons From Two Technical Transformations by Leah Hu...
apidays New York 2025 - Lessons From Two Technical Transformations by Leah Hu...apidays New York 2025 - Lessons From Two Technical Transformations by Leah Hu...
apidays New York 2025 - Lessons From Two Technical Transformations by Leah Hu...
apidays
 
apidays New York 2025 - Computers are still dumb by Ben Morss (DeepL)
apidays New York 2025 - Computers are still dumb by Ben Morss (DeepL)apidays New York 2025 - Computers are still dumb by Ben Morss (DeepL)
apidays New York 2025 - Computers are still dumb by Ben Morss (DeepL)
apidays
 
apidays New York 2025 - Breaking Barriers: Lessons Learned from API Integrati...
apidays New York 2025 - Breaking Barriers: Lessons Learned from API Integrati...apidays New York 2025 - Breaking Barriers: Lessons Learned from API Integrati...
apidays New York 2025 - Breaking Barriers: Lessons Learned from API Integrati...
apidays
 
apidays New York 2025 - Why an SDK is Needed to Protect APIs from Mobile Apps...
apidays New York 2025 - Why an SDK is Needed to Protect APIs from Mobile Apps...apidays New York 2025 - Why an SDK is Needed to Protect APIs from Mobile Apps...
apidays New York 2025 - Why an SDK is Needed to Protect APIs from Mobile Apps...
apidays
 
Mining Presentation Online Courses for Student
Mining Presentation Online Courses for StudentMining Presentation Online Courses for Student
Mining Presentation Online Courses for Student
Rizki229625
 
apidays Singapore 2025 - 4 Identity Essentials for Scaling SaaS in Large Orgs...
apidays Singapore 2025 - 4 Identity Essentials for Scaling SaaS in Large Orgs...apidays Singapore 2025 - 4 Identity Essentials for Scaling SaaS in Large Orgs...
apidays Singapore 2025 - 4 Identity Essentials for Scaling SaaS in Large Orgs...
apidays
 
apidays New York 2025 - Building Scalable AI Systems by Sai Prasad Veluru (Ap...
apidays New York 2025 - Building Scalable AI Systems by Sai Prasad Veluru (Ap...apidays New York 2025 - Building Scalable AI Systems by Sai Prasad Veluru (Ap...
apidays New York 2025 - Building Scalable AI Systems by Sai Prasad Veluru (Ap...
apidays
 
MICROSOFT POWERPOINT AND USES(BEST)..pdf
MICROSOFT POWERPOINT AND USES(BEST)..pdfMICROSOFT POWERPOINT AND USES(BEST)..pdf
MICROSOFT POWERPOINT AND USES(BEST)..pdf
bathyates
 
Ch01_Introduction_to_Information_Securit
Ch01_Introduction_to_Information_SecuritCh01_Introduction_to_Information_Securit
Ch01_Introduction_to_Information_Securit
KawukiDerrick
 
AG-FIRMA FINCOME ARTICLE AI AGENT RAG.pdf
AG-FIRMA FINCOME ARTICLE AI AGENT RAG.pdfAG-FIRMA FINCOME ARTICLE AI AGENT RAG.pdf
AG-FIRMA FINCOME ARTICLE AI AGENT RAG.pdf
Anass Nabil
 
LONGSEM2024-25_CSE3015_ETH_AP2024256000125_Reference-Material-I.pptx
LONGSEM2024-25_CSE3015_ETH_AP2024256000125_Reference-Material-I.pptxLONGSEM2024-25_CSE3015_ETH_AP2024256000125_Reference-Material-I.pptx
LONGSEM2024-25_CSE3015_ETH_AP2024256000125_Reference-Material-I.pptx
vemuripraveena2622
 
apidays New York 2025 - Fast, Repeatable, Secure: Pick 3 with FINOS CCC by Le...
apidays New York 2025 - Fast, Repeatable, Secure: Pick 3 with FINOS CCC by Le...apidays New York 2025 - Fast, Repeatable, Secure: Pick 3 with FINOS CCC by Le...
apidays New York 2025 - Fast, Repeatable, Secure: Pick 3 with FINOS CCC by Le...
apidays
 
apidays New York 2025 - Boost API Development Velocity with Practical AI Tool...
apidays New York 2025 - Boost API Development Velocity with Practical AI Tool...apidays New York 2025 - Boost API Development Velocity with Practical AI Tool...
apidays New York 2025 - Boost API Development Velocity with Practical AI Tool...
apidays
 
[Eddie Lee] Capstone Project - AI PM Bootcamp - DataFox.pdf
[Eddie Lee] Capstone Project - AI PM Bootcamp - DataFox.pdf[Eddie Lee] Capstone Project - AI PM Bootcamp - DataFox.pdf
[Eddie Lee] Capstone Project - AI PM Bootcamp - DataFox.pdf
Eddie Lee
 
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdfMEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
OlhaTatokhina1
 
Advanced_English_Pronunciation_in_Use.pdf
Advanced_English_Pronunciation_in_Use.pdfAdvanced_English_Pronunciation_in_Use.pdf
Advanced_English_Pronunciation_in_Use.pdf
leogoemmanguyenthao
 
1-2. Lab Introduction to Linux environment.ppt
1-2. Lab Introduction to Linux environment.ppt1-2. Lab Introduction to Linux environment.ppt
1-2. Lab Introduction to Linux environment.ppt
Wahajch
 
apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays
 
apidays New York 2025 - Unifying OpenAPI & AsyncAPI by Naresh Jain & Hari Kri...
apidays New York 2025 - Unifying OpenAPI & AsyncAPI by Naresh Jain & Hari Kri...apidays New York 2025 - Unifying OpenAPI & AsyncAPI by Naresh Jain & Hari Kri...
apidays New York 2025 - Unifying OpenAPI & AsyncAPI by Naresh Jain & Hari Kri...
apidays
 
SAP_S4HANA_EWM_Food_Processing_Industry.pptx
SAP_S4HANA_EWM_Food_Processing_Industry.pptxSAP_S4HANA_EWM_Food_Processing_Industry.pptx
SAP_S4HANA_EWM_Food_Processing_Industry.pptx
vemulavenu484
 
apidays New York 2025 - Lessons From Two Technical Transformations by Leah Hu...
apidays New York 2025 - Lessons From Two Technical Transformations by Leah Hu...apidays New York 2025 - Lessons From Two Technical Transformations by Leah Hu...
apidays New York 2025 - Lessons From Two Technical Transformations by Leah Hu...
apidays
 
apidays New York 2025 - Computers are still dumb by Ben Morss (DeepL)
apidays New York 2025 - Computers are still dumb by Ben Morss (DeepL)apidays New York 2025 - Computers are still dumb by Ben Morss (DeepL)
apidays New York 2025 - Computers are still dumb by Ben Morss (DeepL)
apidays
 
apidays New York 2025 - Breaking Barriers: Lessons Learned from API Integrati...
apidays New York 2025 - Breaking Barriers: Lessons Learned from API Integrati...apidays New York 2025 - Breaking Barriers: Lessons Learned from API Integrati...
apidays New York 2025 - Breaking Barriers: Lessons Learned from API Integrati...
apidays
 
apidays New York 2025 - Why an SDK is Needed to Protect APIs from Mobile Apps...
apidays New York 2025 - Why an SDK is Needed to Protect APIs from Mobile Apps...apidays New York 2025 - Why an SDK is Needed to Protect APIs from Mobile Apps...
apidays New York 2025 - Why an SDK is Needed to Protect APIs from Mobile Apps...
apidays
 
Mining Presentation Online Courses for Student
Mining Presentation Online Courses for StudentMining Presentation Online Courses for Student
Mining Presentation Online Courses for Student
Rizki229625
 
apidays Singapore 2025 - 4 Identity Essentials for Scaling SaaS in Large Orgs...
apidays Singapore 2025 - 4 Identity Essentials for Scaling SaaS in Large Orgs...apidays Singapore 2025 - 4 Identity Essentials for Scaling SaaS in Large Orgs...
apidays Singapore 2025 - 4 Identity Essentials for Scaling SaaS in Large Orgs...
apidays
 
apidays New York 2025 - Building Scalable AI Systems by Sai Prasad Veluru (Ap...
apidays New York 2025 - Building Scalable AI Systems by Sai Prasad Veluru (Ap...apidays New York 2025 - Building Scalable AI Systems by Sai Prasad Veluru (Ap...
apidays New York 2025 - Building Scalable AI Systems by Sai Prasad Veluru (Ap...
apidays
 
MICROSOFT POWERPOINT AND USES(BEST)..pdf
MICROSOFT POWERPOINT AND USES(BEST)..pdfMICROSOFT POWERPOINT AND USES(BEST)..pdf
MICROSOFT POWERPOINT AND USES(BEST)..pdf
bathyates
 
Ch01_Introduction_to_Information_Securit
Ch01_Introduction_to_Information_SecuritCh01_Introduction_to_Information_Securit
Ch01_Introduction_to_Information_Securit
KawukiDerrick
 
AG-FIRMA FINCOME ARTICLE AI AGENT RAG.pdf
AG-FIRMA FINCOME ARTICLE AI AGENT RAG.pdfAG-FIRMA FINCOME ARTICLE AI AGENT RAG.pdf
AG-FIRMA FINCOME ARTICLE AI AGENT RAG.pdf
Anass Nabil
 
LONGSEM2024-25_CSE3015_ETH_AP2024256000125_Reference-Material-I.pptx
LONGSEM2024-25_CSE3015_ETH_AP2024256000125_Reference-Material-I.pptxLONGSEM2024-25_CSE3015_ETH_AP2024256000125_Reference-Material-I.pptx
LONGSEM2024-25_CSE3015_ETH_AP2024256000125_Reference-Material-I.pptx
vemuripraveena2622
 
apidays New York 2025 - Fast, Repeatable, Secure: Pick 3 with FINOS CCC by Le...
apidays New York 2025 - Fast, Repeatable, Secure: Pick 3 with FINOS CCC by Le...apidays New York 2025 - Fast, Repeatable, Secure: Pick 3 with FINOS CCC by Le...
apidays New York 2025 - Fast, Repeatable, Secure: Pick 3 with FINOS CCC by Le...
apidays
 
apidays New York 2025 - Boost API Development Velocity with Practical AI Tool...
apidays New York 2025 - Boost API Development Velocity with Practical AI Tool...apidays New York 2025 - Boost API Development Velocity with Practical AI Tool...
apidays New York 2025 - Boost API Development Velocity with Practical AI Tool...
apidays
 
[Eddie Lee] Capstone Project - AI PM Bootcamp - DataFox.pdf
[Eddie Lee] Capstone Project - AI PM Bootcamp - DataFox.pdf[Eddie Lee] Capstone Project - AI PM Bootcamp - DataFox.pdf
[Eddie Lee] Capstone Project - AI PM Bootcamp - DataFox.pdf
Eddie Lee
 
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdfMEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
OlhaTatokhina1
 
Advanced_English_Pronunciation_in_Use.pdf
Advanced_English_Pronunciation_in_Use.pdfAdvanced_English_Pronunciation_in_Use.pdf
Advanced_English_Pronunciation_in_Use.pdf
leogoemmanguyenthao
 
1-2. Lab Introduction to Linux environment.ppt
1-2. Lab Introduction to Linux environment.ppt1-2. Lab Introduction to Linux environment.ppt
1-2. Lab Introduction to Linux environment.ppt
Wahajch
 
Ad

Advanced Java Programming: Introduction and Overview of Java Networking 1. Introduction to Advanced Java Programming

  • 1.  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
  • 2. Network Basics  interconnection of computing devices for resources sharing.  The computer which receives service is called a client.  The computer which provides the service is called server.  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/resources on the world wide web.  TCP/IP: Connection oriented , reliable protocol  UDP: connection less , unreliable A Network is
  • 3. 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 for networking applications in Java  classes related to the connection and then identifying a connection   For making a actually communication (sending and receiving data)  Java.net Package InetAddress : Internet Protocol (IP) address URL : Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. URLConnection : Represent the communications link between the application and a URL ServerSocket : create a server socket, establish communication with the clients. Socket :implements client sockets DatagramPacket : represents a datagram packet. DatagramSocket : socket for sending and receiving datagram packets.
  • 4. InetAddress   Use to get the IP Address of website / host name  used to encapsulate both the numerical IP address and host name. 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 has. 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. String toString() Converts this IP address to a String. boolean equals(Object obj) Compares this object against the specified object. static InetAddress getLoopbackAddress() Returns the loopback address. (localhost, address of itself)
  • 5. import java.net.*; public class Address { public static void main(String[] args) { try { // Using getByName() to get IP address from host name InetAddress ip = InetAddress.getByName("www.darshan.ac.in"); System.out.println("IP: " + ip); // Using getAllByName() to get an array of IP addresses from host name InetAddress addressList[] = InetAddress.getAllByName("wixnets.com"); for (int i = 0; i < addressList.length; i++) { System.out.println(addressList[i]); } // Using getLocalHost() to get the IP address and name of the local host InetAddress localhost = InetAddress.getLocalHost(); System.out.println("LocalHost: " + localhost); // Using getHostName() to get host/server name from IP address InetAddress ip2 = InetAddress.getByName("10.254.3.79"); System.out.println("Hostname: " + ip2.getHostName()); // Using getHostAddress() to get IP address from host name InetAddress ip3 = InetAddress.getByName("www.darshan.ac.in"); System.out.println("HostAddress: " + ip3.getHostAddress()); } catch (UnknownHostException e) { System.out.println(e); } } } IP: www.darshan.ac.in/89.238.188.50 wixnets.com/104.18.48.113 wixnets.com/172.67.198.137 wixnets.com/104.18.49.113 LocalHost: LAPTOP-NB4I63VB/10.254.3.79 Hostname: LAPTOP-NB4I63VB HostAddress: 89.238.188.50
  • 6. Program Write a program to accept a website name and return its IPAddress, after checking it on Internet
  • 7. URL  Uniform Resource Locator  uniquely identify resources on the internet.  pointer to “resource” on the World Wide Web. Get info about URL 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) URL url=new URL("http://www.darshan.ac.in"); URLConnection urlcon=url.openConnection(); http://www.example.com:8090/path/index.html?key1=value1&key2=value2 Port Number Protocol Server name or IP Address (Domain name) parameter Path to fie OR OR
  • 8. 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( host name + port) part of the URL. public String toString() it returns the string representation of the URL. public String getQuery() it returns the query string( variable + value pair) of the URL. public String getDefaultPort() it returns the default port of the URL. public URLConnection openConnection() used to establish a URL connection to the specified URL public URI toURI() it returns a URI (uniform recourse identifier) of the URL. URI class is useful when you need to perform more generic operations on a Uniform Resource Identifier.
  • 9. Program Write a program to get the Protocol, Host Name, Port Number, and Default File Name from given URL.
  • 10. URLConnection  class is useful to actually connect to a website / resource on a network and get all the details about content  - establish a connection with the site on internet.  returns object. URL obj=new URL(String urlSpecifier) throws MalformedURLException URLConnection conn=obj.openConnection(); URL url=new URL("http://www.darshan.ac.in"); URLConnection urlcon=url.openConnection();
  • 11. 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) retrieve the value of a header field at the specified index. public String getHeaderField(String fieldName) it returns the value of the header field specified by field name. public InputStream getInputStream() throws IOException Returns an input stream that reads from this open connection. public OutputStream getOutputStream() throws IOException Returns an output stream that writes into this open connection.
  • 12. Program Write a program to display the details and page contents of your website.
  • 13. Client – Server Architecture  Two machines must connect  Server waits for connection  Client initiates connection  Server responds to the client request 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.  The Socket class is for clients, and ServerSocket class is for server.
  • 14. Socket Overview  Server has many ports, server program connects to one of these ports, a process known as "binding to a port." This connection is established through a server socket.  Server is waiting for client machine to connect.  When a client wants to communicate with the server, it connects to the server's port. This connection is established through a client socket.  Every time a client connects, its socket is extracted.  The server loop then waits for the next client. Computer S E R V E R Computer where server is running Server Socket The Java code for creating server in Network Programming: 1010 80 5566 1080 2010 3040 Port Number The Java code for creating socket at client side. Socket
  • 15. TCP/IP socket setup at Client & Server side  At server side, create server socket with some port number using class of . package. Here port number, tells which service of server.  server wait till a client accepts connection, this is done using method.(Accept client request)  used to establish communication with the clients  At client side, create socket with host name and port number using class. ip - which server , port - which service OR
  • 16. Sockets class method  getInetAddress(): Returns the address of the Socket object.  getPort(): Returns the remote port to which the Socket object is connected.  getLocalPort(): Returns the local port number.  getInputStream(): Returns an input stream that reads data from this open connection.  getOutputStream(): Returns an output stream that writes data to the open connection.  connect(SocketAddress endpoint, int timeout): Connects the socket to the specified endpoint with a timeout. (I/O) package in Java  streams are the sequence of data  The java.io package contains classes to perform input and output (I/O) in Java.  There are two type of Streams  − The InputStream is used to read data from a source.  − The OutputStream is used for writing data to a destination.  – it formats the string
  • 17. import java.net.*; import java.io.*; public class MyServer { public static void main(String[] args) { try { // Create a server socket that listens on port 888 ServerSocket ss = new ServerSocket(888); // Wait for a client to connect and accept the connection Socket s = ss.accept(); // For sending a data attach output stream to the server socket using method. OutputStream obj = s.getOutputStream(); //write data // Create a PrintStream to write text data to the output stream PrintStream ps = new PrintStream(obj); //format data // Send the message "Hello client" to the client ps.println("Hello client"); ss.close(); // Close ServerSocket s.close(); // Close Socket ps.close(); // Close Printstream } catch (IOException ex) { // Print any exceptions that occur during execution ex.printStackTrace(); } } } This line blocks the server's execution until a client attempts to connect to the server. When a client connection request is received, the accept() method returns a new Socket object. Creating a Server That Sends Data 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.
  • 18. import java.net.*; import java.io.*; public class MyClient { public static void main(String[] args) { try { Socket s = new Socket("localhost", 888); // Connect to server on localhost at port 888, here server in on local computer so InputStream inStr = s.getInputStream(); //read data // For receiving data, attach input stream to the socket, using method BufferedReader br = new BufferedReader(new InputStreamReader(inStr)); // Create BufferedReader to read text data String receivedMessage = br.readLine(); // Read message from BufferedReader using read() & readline() System.out.println("Message: " + receivedMessage); // Print received message br.close(); // Close BufferedReader s.close(); // Close Socket } catch (IOException ex) { ex.printStackTrace(); // Print any exceptions that occur } } } Creating a Client That Receive Data
  • 19. Datagrams  datagrams are independent messages sent over a network, with no guarantee of arrival, arrival time.  If you send multiple packet, it may arrive in any order, packet delivery is not guaranteed.  Java implements datagrams using the UDP (User Datagram Protocol) protocol through two main classes:  DatagramPacket: container for the data being transmitted. It encapsulates the data along with information about its destination.  DatagramSocket: used to send or receive DatagramPackets. DatagramSocket:  represents a connection-less socket used for sending and receiving datagram packets.  DatagramSocket ds = new DatagramSocket();  creates a datagram socket and binds it with an available port number on the localhost machine.  DatagramSocket ds = new DatagramSocket(int port);  creates a datagram socket and binds it with the given port number.  DatagramSocket ds = new DatagramSocket(int port, InetAddress ipAddress);  creates a datagram socket and binds it with the specified port number and host address.
  • 20. DatagramSocket class methods:  getInetAddress(): Returns the address to which the socket is connected.  getPort(): Returns the port number to which the socket is connected.  getLocalPort(): Returns the local port number.  isBound(): Returns true if the socket is bound to an address.  isConnected(): Returns true if the socket is connected to a server. DatagramPacket class  DatagramPacket dp = new DatagramPacket(byte data[], int size): buffer that will receive data and the size of a packet.  DatagramPacket dp = new DatagramPacket(byte data[], int offset, int size): specify an offset into the buffer at which data will be stored  DatagramPacket dp = new DatagramPacket(byte data[], int size, InetAddress ipAddress, int port): specified target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent.
  • 21. import java.net.*; public class UDPSender { public static void main(String[] args) { try { // Create a DatagramSocket DatagramSocket ds = new DatagramSocket(); // Create a message to send String str = "Message from Sender"; // Get the IP address of the localhost (reciver’s ip address) InetAddress ip = InetAddress.getByName("localhost"); // Create a DatagramPacket with the message, IP address, and port number DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 6666); // Send the packet ds.send(dp); // Close the socket ds.close(); } catch (Exception ex) { // Print any exceptions that occur ex.printStackTrace(); } } } Sending DatagramPacket by DatagramSocket Write a program to create Sender and Receiver for connectionless communication.
  • 22. import java.net.*; import java.io.*; public class UDPReceiver { public static void main(String[] args) { try { // Create a Datagram Socket object with specific port number. DatagramSocket ds = new DatagramSocket(6666); // Create a buffer to store received data byte buffer[] = new byte[1024]; // Create a DatagramPacket to receive data into the buffer DatagramPacket dp = new DatagramPacket(buffer, 1024); // Receive data into the DatagramPacket ds.receive(dp); // Convert the received data into a String String str = new String(dp.getData(), 0, dp.getLength()); // Print the received message System.out.println("Received: " + str); // Close the DatagramSocket ds.close(); } catch (Exception ex) { // Print any exceptions that occur ex.printStackTrace(); } } } Receiving DatagramPacket by DatagramSocket
  • 23. 1. Explain the usage of Socket class with example. 2. Implement the client server program using UDP Sockets. Client will request to download the file from server and server will send it to client. 3. Compare ServerSocket with Socket(2) 4. How do you get the IP address of a machine from its hostname? InetAddress ip = InetAddress.getByName("www.darshan.ac.in"); 5. What are the differences between a TCP socket and UDP socket? How are they created in Java?