SlideShare a Scribd company logo
Networking
• Introduction
• Networking Basics
• Networking Classes and Interfaces
• TCP Client/Server Sockets
• UDP Client/Server Sockets
• Java is practically a synonym for Internet
programming. There are a number of reasons
for this like its ability to generate secure,
cross-platform, portable code.
• One of the most important reasons that Java
is the premier language for network
programming are the classes defined in the
java.net package. They provide an easy-to-use
means by which programmers of all skill levels
can access network resources.
Networking Basics
• At the core of Java’s networking support is the concept
of a socket. A socket identifies an endpoint in a
network. The socket paradigm was part of the 4.2BSD
Berkeley UNIX release in the early 1980s. Because of
this, the term Berkeley socket is also used.
• Sockets are at the foundation of modern networking
because a socket allows a single computer to serve
many different clients at once, as well as to serve many
different types of information. This is accomplished
through the use of a port, which is a numbered socket
on a particular machine. A server process is said to
“listen” to a port until a client connects to it.
• Socket communication takes place via a protocol.
Internet Protocol (IP) is a low-level routing protocol
that breaks data into small packets and sends them to
an address across a network, which does not guarantee
to deliver said packets to the destination.
• Transmission Control Protocol (TCP) is a higher-level
protocol that manages to robustly string together
these packets, sorting and retransmitting them as
necessary to reliably transmit data.
• A third protocol, User Datagram Protocol (UDP), sits
next to TCP and can be used directly to support fast,
connectionless, unreliable transport of packets.
• TCP/IP reserves the lower 1,024 ports for specific
protocols. Many of these will seem familiar to
you if you have spent any time surfing the
Internet. Port number 21 is for FTP; 23 is for
Telnet; 25 is for e-mail; 43 is for whois; 79 is for
finger; 80 is for HTTP; 119 is for netnews so on.
• It is up to each protocol to determine how a
client should interact with the port. For example,
HTTP is the protocol that web browsers and
servers use to transfer hypertext pages and
images.
• A key component of the Internet is the address.
Every computer on the Internet has one. An
internet address is a number that uniquely
identifies each computer on the Net.
• Originally, all Internet addresses consisted of 32-
bit values, organized as four 8-bit values. This
address type was specified by IPv4 (Internet
Protocol, version 4). However, a new addressing
scheme, called IPv6 (Internet Protocol, version 6)
has come into play. IPv6 uses a 128-bit value to
represent an address, organized into eight 16-bit
chunks.
• Just as the numbers of an IP address describe a
network hierarchy, the name of an Internet
address, called its domain name, describes a
machine’s location in a name space. For example,
www.osborne.com is in the COM domain
(reserved for U.S. commercial sites); it is called
osborne (after the company name), and www
identifies the server for web requests. An Internet
domain name is mapped to an IP address by the
Domain Naming Service (DNS). This enables users
to work with domain names, but the Internet
operates on IP addresses.
The Networking Classes and
Interfaces
28  networking
• InetAddress: The InetAddress class is used to
encapsulate both the numerical IP address and the
domain name for that address.
// Demonstrate InetAddress.
import java.net.*;
class B
{
public static void main(String args[]) throws
UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("google.com");
System.out.println(Address);
} }
TCP Client/Server Sockets
• TCP/IP sockets are used to implement reliable,
bidirectional, persistent, point-to-point, stream-based
connections between hosts on the Internet.
• A socket can be used to connect Java’s I/O system to
other programs that may reside either on the local
machine or on any other machine on the Internet.
• There are two kinds of TCP sockets in Java. One is for
servers, and the other is for clients.
• The ServerSocket class is designed to be a “listener,”
which waits for clients to connect before doing
anything. Thus, ServerSocket is for servers.
• The Socket class is for clients. It is designed to connect
to server sockets and initiate protocol exchanges.
• Socket(String hostName, int port) throws
UnknownHostException, IOException
• Socket(InetAddress ipAddress, int port) throws
IOException
• You can gain access to the input and output
streams associated with a Socket by use of the
getInputStream( ) and getOuptutStream()
methods, as shown here. Each can throw an
IOException if the socket has been invalidated by
a loss of connection.
• Several other method are available, like connect()
which allows you to specify a new connection.
• Simple TCP Server.
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{ Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + 'n';
outToClient.writeBytes(capitalizedSentence);
} } }
• Simple TCP Client
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence, modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new
InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + 'n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close(); } }
UDP Client/Server Sockets
• TCP/IP-style networking is appropriate for most
networking needs. It provides a serialized,
predictable, reliable stream of packet data.
However. TCP includes many complicated
algorithms for dealing with congestion control on
crowded networks, as well as pessimistic
expectations about packet loss. This leads to a
somewhat inefficient way to transport data.
Datagrams provide an alternative.
• Datagrams are bundles of information passed
between machines.
• 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. Likewise, 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
protocol by using two classes: DatagramPacket
and DatagramSocket
• DatagramPacket object is the data container,
while the DatagramSocket is the mechanism
used to send or receive the DatagramPackets.
DatagramSocket( ) throws SocketException
DatagramSocket(int port) throws SocketException
• DatagramSocket defines many methods. Two of
the most important are send( ) and receive()
void send(DatagramPacket packet) throws
IOException
void receive(DatagramPacket packet) throws
IOException
• DatagramPacket defines several constructors.
DatagramPacket(byte data[ ], int size)
DatagramPacket(byte data[ ], int offset, int size)
• simple UDP server.
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, port);
serverSocket.send(sendPacket); } } }
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception {
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence.trim());
clientSocket.close(); } }
28  networking

More Related Content

What's hot (20)

PDF
Java Programming - 07 java networking
Danairat Thanabodithammachari
 
PPT
Java networking
Arati Gadgil
 
PPT
Socket Programming
CEC Landran
 
PPT
Networking Java Socket Programming
Mousmi Pawar
 
PDF
Java networking programs socket based
Mukesh Tekwani
 
PPT
Md13 networking
Rakesh Madugula
 
PPT
Java API: java.net.InetAddress
Sayak Sarkar
 
PPTX
Socket programming in Java (PPTX)
UC San Diego
 
PDF
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
PPT
Network programming in Java
Tushar B Kute
 
PPT
Java Networking
Sunil OS
 
PPT
Socket Programming - nitish nagar
Nitish Nagar
 
PPT
Network Programming in Java
Tushar B Kute
 
PDF
Networking in java, Advanced programming
Gera Paulos
 
PPT
Basic Networking in Java
suraj pandey
 
PDF
Ipc
deepakittude
 
PPTX
Networking in python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
PDF
Module 1 networking basics-2
Ankit Dubey
 
PPTX
Socket programming or network programming
Mmanan91
 
Java Programming - 07 java networking
Danairat Thanabodithammachari
 
Java networking
Arati Gadgil
 
Socket Programming
CEC Landran
 
Networking Java Socket Programming
Mousmi Pawar
 
Java networking programs socket based
Mukesh Tekwani
 
Md13 networking
Rakesh Madugula
 
Java API: java.net.InetAddress
Sayak Sarkar
 
Socket programming in Java (PPTX)
UC San Diego
 
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
Network programming in Java
Tushar B Kute
 
Java Networking
Sunil OS
 
Socket Programming - nitish nagar
Nitish Nagar
 
Network Programming in Java
Tushar B Kute
 
Networking in java, Advanced programming
Gera Paulos
 
Basic Networking in Java
suraj pandey
 
Module 1 networking basics-2
Ankit Dubey
 
Socket programming or network programming
Mmanan91
 

Viewers also liked (20)

PDF
26 io -ii file handling
Ravindra Rathore
 
PPT
Introduction of reflection
Ravindra Rathore
 
PPTX
Ch11 communication
adrienne0901
 
PPTX
Lecture 5 phasor notations
Ravindra Rathore
 
PDF
21 multi threading - iii
Ravindra Rathore
 
PDF
22 multi threading iv
Ravindra Rathore
 
PPTX
Vlsi
Rina Ahire
 
PPTX
Fiber optics101
admercano101
 
PDF
Spread spectrum
Rina Ahire
 
PDF
16 exception handling - i
Ravindra Rathore
 
PPTX
T com presentation (error correcting code)
Akshit Jain
 
PPTX
Low noise amplifier csd
Rina Ahire
 
PPT
Digital Communication 2
admercano101
 
PPTX
Line coding
Gagan Randhawa
 
PPT
Digital Communication 4
admercano101
 
PPT
Limits
admercano101
 
PDF
Trigonometry101
admercano101
 
PPTX
Analytic geometry lecture2
admercano101
 
PPTX
Data Communication 1
admercano101
 
PDF
27 applet programming
Ravindra Rathore
 
26 io -ii file handling
Ravindra Rathore
 
Introduction of reflection
Ravindra Rathore
 
Ch11 communication
adrienne0901
 
Lecture 5 phasor notations
Ravindra Rathore
 
21 multi threading - iii
Ravindra Rathore
 
22 multi threading iv
Ravindra Rathore
 
Fiber optics101
admercano101
 
Spread spectrum
Rina Ahire
 
16 exception handling - i
Ravindra Rathore
 
T com presentation (error correcting code)
Akshit Jain
 
Low noise amplifier csd
Rina Ahire
 
Digital Communication 2
admercano101
 
Line coding
Gagan Randhawa
 
Digital Communication 4
admercano101
 
Limits
admercano101
 
Trigonometry101
admercano101
 
Analytic geometry lecture2
admercano101
 
Data Communication 1
admercano101
 
27 applet programming
Ravindra Rathore
 
Ad

Similar to 28 networking (20)

PDF
Networking Basics1ofjavaprogramming.pptx.pdf
omkarthombare4989
 
PPTX
Java socket programming
Mohammed Abdalla Youssif
 
PPTX
5_6278455688045789623.pptx
EliasPetros
 
PPT
Unit 8 Java
arnold 7490
 
PPTX
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
VijiPriya Jeyamani
 
PPTX
Networking.pptx
Esubesisay
 
DOC
Socket
Amandeep Kaur
 
PPT
chapter-4-networking hjgjjgj did hfhhfhj
AmitDeshai
 
PPTX
A.java
JahnaviBhagat
 
PPTX
Java seminar.pptx
shirindigitel
 
PPTX
Java 1
VidyaVarshini3
 
PPTX
Socket & Server Socket
Hemant Chetwani
 
PPT
Socket Programming in Java.ppt yeh haii
inambscs4508
 
PDF
Networking
Tuan Ngo
 
PPTX
Network programming in java - PPT
kamal kotecha
 
PDF
Ajp notes-chapter-04
Ankit Dubey
 
DOCX
Lab manual cn-2012-13
Sasi Kala
 
PPTX
Tcp/ip server sockets
rajshreemuthiah
 
PPTX
Javanetworkingbasicssocketsoverview
rajshreemuthiah
 
PPTX
Java networking basics & sockets overview
rajshreemuthiah
 
Networking Basics1ofjavaprogramming.pptx.pdf
omkarthombare4989
 
Java socket programming
Mohammed Abdalla Youssif
 
5_6278455688045789623.pptx
EliasPetros
 
Unit 8 Java
arnold 7490
 
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
VijiPriya Jeyamani
 
Networking.pptx
Esubesisay
 
chapter-4-networking hjgjjgj did hfhhfhj
AmitDeshai
 
Java seminar.pptx
shirindigitel
 
Socket & Server Socket
Hemant Chetwani
 
Socket Programming in Java.ppt yeh haii
inambscs4508
 
Networking
Tuan Ngo
 
Network programming in java - PPT
kamal kotecha
 
Ajp notes-chapter-04
Ankit Dubey
 
Lab manual cn-2012-13
Sasi Kala
 
Tcp/ip server sockets
rajshreemuthiah
 
Javanetworkingbasicssocketsoverview
rajshreemuthiah
 
Java networking basics & sockets overview
rajshreemuthiah
 
Ad

Recently uploaded (20)

PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 

28 networking

  • 1. Networking • Introduction • Networking Basics • Networking Classes and Interfaces • TCP Client/Server Sockets • UDP Client/Server Sockets
  • 2. • Java is practically a synonym for Internet programming. There are a number of reasons for this like its ability to generate secure, cross-platform, portable code. • One of the most important reasons that Java is the premier language for network programming are the classes defined in the java.net package. They provide an easy-to-use means by which programmers of all skill levels can access network resources.
  • 3. Networking Basics • At the core of Java’s networking support is the concept of a socket. A socket identifies an endpoint in a network. The socket paradigm was part of the 4.2BSD Berkeley UNIX release in the early 1980s. Because of this, the term Berkeley socket is also used. • Sockets are at the foundation of modern networking because a socket allows a single computer to serve many different clients at once, as well as to serve many different types of information. This is accomplished through the use of a port, which is a numbered socket on a particular machine. A server process is said to “listen” to a port until a client connects to it.
  • 4. • Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level routing protocol that breaks data into small packets and sends them to an address across a network, which does not guarantee to deliver said packets to the destination. • Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string together these packets, sorting and retransmitting them as necessary to reliably transmit data. • A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast, connectionless, unreliable transport of packets.
  • 5. • TCP/IP reserves the lower 1,024 ports for specific protocols. Many of these will seem familiar to you if you have spent any time surfing the Internet. Port number 21 is for FTP; 23 is for Telnet; 25 is for e-mail; 43 is for whois; 79 is for finger; 80 is for HTTP; 119 is for netnews so on. • It is up to each protocol to determine how a client should interact with the port. For example, HTTP is the protocol that web browsers and servers use to transfer hypertext pages and images.
  • 6. • A key component of the Internet is the address. Every computer on the Internet has one. An internet address is a number that uniquely identifies each computer on the Net. • Originally, all Internet addresses consisted of 32- bit values, organized as four 8-bit values. This address type was specified by IPv4 (Internet Protocol, version 4). However, a new addressing scheme, called IPv6 (Internet Protocol, version 6) has come into play. IPv6 uses a 128-bit value to represent an address, organized into eight 16-bit chunks.
  • 7. • Just as the numbers of an IP address describe a network hierarchy, the name of an Internet address, called its domain name, describes a machine’s location in a name space. For example, www.osborne.com is in the COM domain (reserved for U.S. commercial sites); it is called osborne (after the company name), and www identifies the server for web requests. An Internet domain name is mapped to an IP address by the Domain Naming Service (DNS). This enables users to work with domain names, but the Internet operates on IP addresses.
  • 8. The Networking Classes and Interfaces
  • 10. • InetAddress: The InetAddress class is used to encapsulate both the numerical IP address and the domain name for that address. // Demonstrate InetAddress. import java.net.*; class B { public static void main(String args[]) throws UnknownHostException { InetAddress Address = InetAddress.getLocalHost(); System.out.println(Address); Address = InetAddress.getByName("google.com"); System.out.println(Address); } }
  • 11. TCP Client/Server Sockets • TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between hosts on the Internet. • A socket can be used to connect Java’s I/O system to other programs that may reside either on the local machine or on any other machine on the Internet. • There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. • The ServerSocket class is designed to be a “listener,” which waits for clients to connect before doing anything. Thus, ServerSocket is for servers. • The Socket class is for clients. It is designed to connect to server sockets and initiate protocol exchanges.
  • 12. • Socket(String hostName, int port) throws UnknownHostException, IOException • Socket(InetAddress ipAddress, int port) throws IOException • You can gain access to the input and output streams associated with a Socket by use of the getInputStream( ) and getOuptutStream() methods, as shown here. Each can throw an IOException if the socket has been invalidated by a loss of connection. • Several other method are available, like connect() which allows you to specify a new connection.
  • 13. • Simple TCP Server. import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); System.out.println("Received: " + clientSentence); capitalizedSentence = clientSentence.toUpperCase() + 'n'; outToClient.writeBytes(capitalizedSentence); } } }
  • 14. • Simple TCP Client import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence, modifiedSentence; BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in)); Socket clientSocket = new Socket("localhost", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + 'n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
  • 15. UDP Client/Server Sockets • TCP/IP-style networking is appropriate for most networking needs. It provides a serialized, predictable, reliable stream of packet data. However. TCP includes many complicated algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to a somewhat inefficient way to transport data. Datagrams provide an alternative. • Datagrams are bundles of information passed between machines.
  • 16. • 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. Likewise, 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 protocol by using two classes: DatagramPacket and DatagramSocket • DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or receive the DatagramPackets.
  • 17. DatagramSocket( ) throws SocketException DatagramSocket(int port) throws SocketException • DatagramSocket defines many methods. Two of the most important are send( ) and receive() void send(DatagramPacket packet) throws IOException void receive(DatagramPacket packet) throws IOException • DatagramPacket defines several constructors. DatagramPacket(byte data[ ], int size) DatagramPacket(byte data[ ], int offset, int size)
  • 18. • simple UDP server. import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength()); System.out.println("RECEIVED: " + sentence); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } }
  • 19. import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence.trim()); clientSocket.close(); } }