SlideShare a Scribd company logo
Network
Programming
in Java
JAVA.NET PACKAGE PROVIDE CLASSES FOR NETWORK
PROGRAMMING
BY((ASHOK HIRPARA))
Network Programming in
Java
 Java’s network support
 Addressing other machines
 Communicating using TCP/IP
 Communicating using UDP
 Broadcasting and multicasting
Network Programming in
Java
 Java distinguishes between UDP, TCP server & TCP
client sockets
 java.net.InetAddress class represents a single
IP address
 java.net.UnkownHostException thrown if DNS
system can’t find IP address for specific host
IP Addresses and Java
 Java has a class java.net.InetAddress
which abstracts network addresses
 Serves three main purposes:
 Encapsulates an address
 Performs name lookup (converting a host name into
an IP address)
 Performs reverse lookup (converting the address
into a host name)
java.net.InetAddress
 Static construction using a factory method
 InetAddress getByName(String hostName)
 hostName can be “host.domain.com.au”, or
 hostName can be “130.95.72.134”
 InetAddress getLocalHost()
 Some useful methods:
 String getHostName()
 Gives you the host name (for example “www.sun.com”)
 String getHostAddress()
 Gives you the address (for example “192.18.97.241”)
 InetAddress getLocalHost()
 InetAddress[] getAllByName(String hostName)
Using InetAddress objects
 import java.net.InetAddress;
 import java.net.UnknownHostExcepion;
 public static void main(String[] args)
 {
 try {
 InetAddress inet1 =
 InetAddress.getByName("asp.ee.uwa.edu.au");
 System.out.println(
 "HostAddress=" + inet1.getHostAddress());
 InetAddress inet2 =
 InetAddress.getByName("130.95.72.134");
 System.out.println("HostName=" + inet2.getHostName());
 if (inet1.equals(inet2))
 System.out.println("Addresses are equal");
 }
 catch (UnknownHostException uhe) {
 uhe.printStackTrace();
 }
 }
Transmission Control Protocol
 TCP is built on top of IP
 Provides the illusion of a continuous flow (or
stream) of data between sender and receiver
(rather like a telephone call)
 Splits up streams into strings of small datagrams
which are sent in succession
 Contains an error recovery mechanism to recover
datagrams which are lost
 These features make application development
simpler and so it is widely used
Two types of TCP Socket
 java.net.ServerSocket is used by servers
so that they can accept incoming TCP/IP
connections
 A server is a piece of software which advertises and
then provides some service on request
 java.net.Socket is used by clients who wish
to establish a connection to a (remote) server
 A client is a piece of software (usually on a different
machine) which makes use of some service
java.net.ServerSocket
 Listens on well-known port for incoming
connections
 Creates a dynamically allocated port for each
newly established connection
 Provides a Socket connected to the new port
 Maintains a queue to ensure that prospective
clients are not lost
java.net.ServerSocket
 Construction:
 ServerSocket(int port, int backlog)
 Allows up to backlog requests to queue
waiting for the server to deal with them
 Some useful methods:
 Socket accept()
 Blocks waiting for a client to attempt to
establish a connection
 void close()
 Called by the server when it is shutting down
to ensure that any resources are deallocated
java.net.Socket
 Provides access to TCP/IP streams
 Bi-directional communication between sender
and receiver
 Can be used to connect to a remote address
and port by using the constructor:
 Socket(String remoteHost, int port)
 Also used to accept an incoming connection
(see ServerSocket)
java.net.Socket
 Can obtain access to input and output streams
 Input stream allows reception of data from the
other party
 InputSteam getInputStream()
 Output stream allows dispatch of data to the
other party
 OutputStream getOutputStream()
How it all fits together
2037 80
2037 1583
2037 1583
Client (A) Server (B)
ServerSocket ss.
s = ss.accept()
s = new Socket
(“B”, 80)
Socket s
s.getInputStream()
s.getOuputStream()
s.getInputStream()
s.getOuputStream()
A sample TCP server
public static void main(String[] args)
{
try {
ServerSocket agreedPort =
new ServerSocket(AGREED_PORT_NUMBER, 5);
while (isStillServing()) {
Socket session = agreedPort.accept();
respond(session);
session.close();
}
agreedPort.close();
}
catch (UnknownHostException uhe) {
// Very unlikely to occur
}
catch (IOException ioe) {
// May occur if the client misbehaves?
}
}
A sample TCP client
public static void main(String[] args)
{
try {
InetAddress server = InetAddress.getByName(args[0]);
Socket connection =
new Socket(server, AGREED_PORT_NUMBER);
makeRequestToServer(connection);
getReplyFromServer(connection);
connection.close();
}
catch (UnknownHostException uhe) {
// arg[0] is not a valid server name or IP address
}
catch (IOException ioe) {
// The connection to the server failed somehow:
// the server might have crashed mid sentence?
}
}
What are datagrams?
 Datagrams are discrete packets of data
 Each is like a parcel that can be addressed and
sent to an recipient anywhere on the Internet
 This is abstracted as the User Datagram Protocol
(UDP) in RFC768 (August 1980)
 Most networks cannot guarantee reliable delivery
of datagrams
Why use datagrams?
 Good for sending data that can naturally be
divided into small chunks
 Poor for (lossless) stream based communications
 Makes economical use of network bandwidth (up
to 3 times the efficiency of TCP/IP for small
messages)
 Datagrams can be locally broadcast or multicast
(one-to-many communication)
Application using
datagrams
 UDP can be used for economical point-to-point
communications over LANs
 Datagrams can be used for one-to-many
communication:
 Local network broadcasting;
 Multicasting (MBONE)
 but there is no way to create one-to-many
streams using TCP/IP
java.net.DatagramPacket
(1)
 DatagramPackets normally used as short lived
envelopes for datagram messages:
 Used to assemble messages before they are
dispatched onto the network,
 or dismantle messages after they have been
received
 Has the following attributes:
 Destination/source address
 Destination/source port number
 Data bytes constituting the message
 Length of message data bytes
java.net.DatagramPacket
(2)
 Construction:
 DatagramPacket(byte[] data, int length)
 Some useful methods:
 void setAddress(InetAddress addr)
 InetAddress getAddress()
 void setPort(int port)
 int getPort()
 DatagramPackets are not immutable so, in principle
you can reuse then, but . .
 Experience has shown that they often misbehave
when you do -- create a new one, use it once, throw
it away!
java.net.DatagramSocket
(1)
 Used to represent a socket associated with a
specific port on the local host
 Used to send or receive datagrams
 Note: there is no counterpart to
java.net.ServerSocket! Just use a
DatagramSocket with a agreed port number so
others know which address and port to send their
datagrams to
java.net.DatagramSocket
(2)
 Construction:
 DatagramSocket(int port)
 Uses a specified port (used for receiving
datagrams)
 DatagramSocket()
 Allocate any available port number (for sending)
 Some useful methods:
 void send(DatagramPacket fullPacket)
 Sends the full datagram out onto the network
 void receive(DatagramPacket emptyPacket)
 Waits until a datagram and fills in emptyPacket
with the message
 . . . and a few more in the Javadoc
sea.datagram.DatagramSend
er
 This example sends datagrams to a specific host
(anywhere on the Internet)
 The steps are as follows:
 Create a new DatagramPacket
 Put some data which constitutes your message in
the new DatagramPacket
 Set a destination address and port so that the
network knows where to deliver the datagram
 Create a socket with a dynamically allocated port
number (if you are just sending from it)
 Send the packet through the socket onto the
network
sea.datagram.DatagramSen
der
byte[] data = “This is the message”.getBytes();
DatagramPacket packet =
new DatagramPacket(data, data.length);
// Create an address
InetAddress destAddress =
InetAddress.getByName(“fred.domain.com”);
packet.setAddress(destAddress);
packet.setPort(9876);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
sea.datagram.DatagramRecei
ver
 The steps are the reserve of sending:
 Create an empty DatagramPacket (and allocate a
buffer for the incoming data)
 Create a DatagramSocket on an agreed socket
number to provide access to arrivals
 Use the socket to receive the datagram (the thread
will block until a new datagram arrrives)
 Extract the data bytes which make up the message
sea.datagram.DatagramRecei
ver
// Create an empty packet with some buffer space
byte[] data = new byte[1500];
DatagramPacket packet =
new DatagramPacket(data, data.length);
DatagramSocket socket = new DatagramSocket(9876);
// This call will block until a datagram arrives
socket.receive(packet);
// Convert the bytes back into a String and print
String message =
new String(packet.getData(), 0, packet.getLength());
System.out.println("message is " + message);
System.out.println("from " + packet.getAddress());
But it’s never quite that
simple!
 Several of the constructors/methods throw
exceptions which I have omitted
 Each datagrams can only hold up to a maximum
of 64KB of data . .
 . . but the underlying transport layer may split the
message into smaller packets (for instance
Ethernet uses about 1500 bytes)
 Always remember that UDP is an unreliable
protocol: If any of the split datagrams are lost the
whole message will be lost

More Related Content

PPT
Java Network Programming
PPT
Java Networking
PPT
Java API: java.net.InetAddress
PPT
Java networking
PPT
Network programming in Java
PDF
Java Programming - 07 java networking
PDF
Java networking programs - theory
PPT
Networking in java
Java Network Programming
Java Networking
Java API: java.net.InetAddress
Java networking
Network programming in Java
Java Programming - 07 java networking
Java networking programs - theory
Networking in java

What's hot (20)

PPTX
Java socket programming
PPTX
Networking in Java
PPTX
Socket programming in Java (PPTX)
PPT
Java Socket Programming
PDF
Java networking programs socket based
PPT
Networking Java Socket Programming
PPT
java networking
PPT
Java Networking
PPT
Socket programming
PDF
28 networking
PDF
Chap 1 Network Theory & Java Overview
PPT
Network programming in Java
PPT
Socket Programming
PPT
Md13 networking
PPT
Socket Programming - nitish nagar
PPT
Network Programming in Java
PPTX
Java networking
PPTX
PPTX
Python Sockets
PPT
Basic Networking in Java
Java socket programming
Networking in Java
Socket programming in Java (PPTX)
Java Socket Programming
Java networking programs socket based
Networking Java Socket Programming
java networking
Java Networking
Socket programming
28 networking
Chap 1 Network Theory & Java Overview
Network programming in Java
Socket Programming
Md13 networking
Socket Programming - nitish nagar
Network Programming in Java
Java networking
Python Sockets
Basic Networking in Java
Ad

Viewers also liked (17)

PPTX
Network programming in java - PPT
PPTX
Multiplayer Java Game
PPT
PPT
Sockets
PDF
Jnp
PPT
java packages
PPT
Ppt of socket
PPT
Socket programming
PPTX
Osi reference model in Networking
PPT
Socket Programming Tutorial
PPT
Basic socket programming
PPT
Introduction to computer network
PPT
Ssl (Secure Sockets Layer)
PPT
Lan chat system
PPTX
Data Communication 1
PPT
Socket System Calls
PDF
Data Communication and Networking
Network programming in java - PPT
Multiplayer Java Game
Sockets
Jnp
java packages
Ppt of socket
Socket programming
Osi reference model in Networking
Socket Programming Tutorial
Basic socket programming
Introduction to computer network
Ssl (Secure Sockets Layer)
Lan chat system
Data Communication 1
Socket System Calls
Data Communication and Networking
Ad

Similar to Advance Java-Network Programming (20)

PPT
Networking.ppt(client/server, socket) uses in program
DOCX
Lab manual cn-2012-13
PPT
Pemrograman Jaringan
PPT
Unit 8 Java
PDF
Lecture6
PPTX
#2 (UDP)
PPT
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
PPTX
PPT
Network
PPT
Socket Programming it-slideshares.blogspot.com
PPT
Socket Programming
PPT
Udp Programming
PPT
Udp Programming
PDF
Module 1 networking basics-2
PPTX
5_6278455688045789623.pptx
PPT
TCP IP
PPT
Client server project
PPTX
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
PPTX
Networking.ppt(client/server, socket) uses in program
Lab manual cn-2012-13
Pemrograman Jaringan
Unit 8 Java
Lecture6
#2 (UDP)
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Network
Socket Programming it-slideshares.blogspot.com
Socket Programming
Udp Programming
Udp Programming
Module 1 networking basics-2
5_6278455688045789623.pptx
TCP IP
Client server project
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...

Recently uploaded (20)

DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
master seminar digital applications in india
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
Classroom Observation Tools for Teachers
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Types and Its function , kingdom of life
PDF
Computing-Curriculum for Schools in Ghana
PDF
Updated Idioms and Phrasal Verbs in English subject
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
master seminar digital applications in india
Paper A Mock Exam 9_ Attempt review.pdf.
Classroom Observation Tools for Teachers
Microbial diseases, their pathogenesis and prophylaxis
Final Presentation General Medicine 03-08-2024.pptx
Yogi Goddess Pres Conference Studio Updates
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
Practical Manual AGRO-233 Principles and Practices of Natural Farming
STATICS OF THE RIGID BODIES Hibbelers.pdf
01-Introduction-to-Information-Management.pdf
Anesthesia in Laparoscopic Surgery in India
Cell Types and Its function , kingdom of life
Computing-Curriculum for Schools in Ghana
Updated Idioms and Phrasal Verbs in English subject

Advance Java-Network Programming

  • 1. Network Programming in Java JAVA.NET PACKAGE PROVIDE CLASSES FOR NETWORK PROGRAMMING BY((ASHOK HIRPARA))
  • 2. Network Programming in Java  Java’s network support  Addressing other machines  Communicating using TCP/IP  Communicating using UDP  Broadcasting and multicasting
  • 3. Network Programming in Java  Java distinguishes between UDP, TCP server & TCP client sockets  java.net.InetAddress class represents a single IP address  java.net.UnkownHostException thrown if DNS system can’t find IP address for specific host
  • 4. IP Addresses and Java  Java has a class java.net.InetAddress which abstracts network addresses  Serves three main purposes:  Encapsulates an address  Performs name lookup (converting a host name into an IP address)  Performs reverse lookup (converting the address into a host name)
  • 5. java.net.InetAddress  Static construction using a factory method  InetAddress getByName(String hostName)  hostName can be “host.domain.com.au”, or  hostName can be “130.95.72.134”  InetAddress getLocalHost()  Some useful methods:  String getHostName()  Gives you the host name (for example “www.sun.com”)  String getHostAddress()  Gives you the address (for example “192.18.97.241”)  InetAddress getLocalHost()  InetAddress[] getAllByName(String hostName)
  • 6. Using InetAddress objects  import java.net.InetAddress;  import java.net.UnknownHostExcepion;  public static void main(String[] args)  {  try {  InetAddress inet1 =  InetAddress.getByName("asp.ee.uwa.edu.au");  System.out.println(  "HostAddress=" + inet1.getHostAddress());  InetAddress inet2 =  InetAddress.getByName("130.95.72.134");  System.out.println("HostName=" + inet2.getHostName());  if (inet1.equals(inet2))  System.out.println("Addresses are equal");  }  catch (UnknownHostException uhe) {  uhe.printStackTrace();  }  }
  • 7. Transmission Control Protocol  TCP is built on top of IP  Provides the illusion of a continuous flow (or stream) of data between sender and receiver (rather like a telephone call)  Splits up streams into strings of small datagrams which are sent in succession  Contains an error recovery mechanism to recover datagrams which are lost  These features make application development simpler and so it is widely used
  • 8. Two types of TCP Socket  java.net.ServerSocket is used by servers so that they can accept incoming TCP/IP connections  A server is a piece of software which advertises and then provides some service on request  java.net.Socket is used by clients who wish to establish a connection to a (remote) server  A client is a piece of software (usually on a different machine) which makes use of some service
  • 9. java.net.ServerSocket  Listens on well-known port for incoming connections  Creates a dynamically allocated port for each newly established connection  Provides a Socket connected to the new port  Maintains a queue to ensure that prospective clients are not lost
  • 10. java.net.ServerSocket  Construction:  ServerSocket(int port, int backlog)  Allows up to backlog requests to queue waiting for the server to deal with them  Some useful methods:  Socket accept()  Blocks waiting for a client to attempt to establish a connection  void close()  Called by the server when it is shutting down to ensure that any resources are deallocated
  • 11. java.net.Socket  Provides access to TCP/IP streams  Bi-directional communication between sender and receiver  Can be used to connect to a remote address and port by using the constructor:  Socket(String remoteHost, int port)  Also used to accept an incoming connection (see ServerSocket)
  • 12. java.net.Socket  Can obtain access to input and output streams  Input stream allows reception of data from the other party  InputSteam getInputStream()  Output stream allows dispatch of data to the other party  OutputStream getOutputStream()
  • 13. How it all fits together 2037 80 2037 1583 2037 1583 Client (A) Server (B) ServerSocket ss. s = ss.accept() s = new Socket (“B”, 80) Socket s s.getInputStream() s.getOuputStream() s.getInputStream() s.getOuputStream()
  • 14. A sample TCP server public static void main(String[] args) { try { ServerSocket agreedPort = new ServerSocket(AGREED_PORT_NUMBER, 5); while (isStillServing()) { Socket session = agreedPort.accept(); respond(session); session.close(); } agreedPort.close(); } catch (UnknownHostException uhe) { // Very unlikely to occur } catch (IOException ioe) { // May occur if the client misbehaves? } }
  • 15. A sample TCP client public static void main(String[] args) { try { InetAddress server = InetAddress.getByName(args[0]); Socket connection = new Socket(server, AGREED_PORT_NUMBER); makeRequestToServer(connection); getReplyFromServer(connection); connection.close(); } catch (UnknownHostException uhe) { // arg[0] is not a valid server name or IP address } catch (IOException ioe) { // The connection to the server failed somehow: // the server might have crashed mid sentence? } }
  • 16. What are datagrams?  Datagrams are discrete packets of data  Each is like a parcel that can be addressed and sent to an recipient anywhere on the Internet  This is abstracted as the User Datagram Protocol (UDP) in RFC768 (August 1980)  Most networks cannot guarantee reliable delivery of datagrams
  • 17. Why use datagrams?  Good for sending data that can naturally be divided into small chunks  Poor for (lossless) stream based communications  Makes economical use of network bandwidth (up to 3 times the efficiency of TCP/IP for small messages)  Datagrams can be locally broadcast or multicast (one-to-many communication)
  • 18. Application using datagrams  UDP can be used for economical point-to-point communications over LANs  Datagrams can be used for one-to-many communication:  Local network broadcasting;  Multicasting (MBONE)  but there is no way to create one-to-many streams using TCP/IP
  • 19. java.net.DatagramPacket (1)  DatagramPackets normally used as short lived envelopes for datagram messages:  Used to assemble messages before they are dispatched onto the network,  or dismantle messages after they have been received  Has the following attributes:  Destination/source address  Destination/source port number  Data bytes constituting the message  Length of message data bytes
  • 20. java.net.DatagramPacket (2)  Construction:  DatagramPacket(byte[] data, int length)  Some useful methods:  void setAddress(InetAddress addr)  InetAddress getAddress()  void setPort(int port)  int getPort()  DatagramPackets are not immutable so, in principle you can reuse then, but . .  Experience has shown that they often misbehave when you do -- create a new one, use it once, throw it away!
  • 21. java.net.DatagramSocket (1)  Used to represent a socket associated with a specific port on the local host  Used to send or receive datagrams  Note: there is no counterpart to java.net.ServerSocket! Just use a DatagramSocket with a agreed port number so others know which address and port to send their datagrams to
  • 22. java.net.DatagramSocket (2)  Construction:  DatagramSocket(int port)  Uses a specified port (used for receiving datagrams)  DatagramSocket()  Allocate any available port number (for sending)  Some useful methods:  void send(DatagramPacket fullPacket)  Sends the full datagram out onto the network  void receive(DatagramPacket emptyPacket)  Waits until a datagram and fills in emptyPacket with the message  . . . and a few more in the Javadoc
  • 23. sea.datagram.DatagramSend er  This example sends datagrams to a specific host (anywhere on the Internet)  The steps are as follows:  Create a new DatagramPacket  Put some data which constitutes your message in the new DatagramPacket  Set a destination address and port so that the network knows where to deliver the datagram  Create a socket with a dynamically allocated port number (if you are just sending from it)  Send the packet through the socket onto the network
  • 24. sea.datagram.DatagramSen der byte[] data = “This is the message”.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length); // Create an address InetAddress destAddress = InetAddress.getByName(“fred.domain.com”); packet.setAddress(destAddress); packet.setPort(9876); DatagramSocket socket = new DatagramSocket(); socket.send(packet);
  • 25. sea.datagram.DatagramRecei ver  The steps are the reserve of sending:  Create an empty DatagramPacket (and allocate a buffer for the incoming data)  Create a DatagramSocket on an agreed socket number to provide access to arrivals  Use the socket to receive the datagram (the thread will block until a new datagram arrrives)  Extract the data bytes which make up the message
  • 26. sea.datagram.DatagramRecei ver // Create an empty packet with some buffer space byte[] data = new byte[1500]; DatagramPacket packet = new DatagramPacket(data, data.length); DatagramSocket socket = new DatagramSocket(9876); // This call will block until a datagram arrives socket.receive(packet); // Convert the bytes back into a String and print String message = new String(packet.getData(), 0, packet.getLength()); System.out.println("message is " + message); System.out.println("from " + packet.getAddress());
  • 27. But it’s never quite that simple!  Several of the constructors/methods throw exceptions which I have omitted  Each datagrams can only hold up to a maximum of 64KB of data . .  . . but the underlying transport layer may split the message into smaller packets (for instance Ethernet uses about 1500 bytes)  Always remember that UDP is an unreliable protocol: If any of the split datagrams are lost the whole message will be lost