SlideShare a Scribd company logo
1 of 37
Tushar B Kute,
Assistant Professor,
Sandip Institute of Technology & Research
Centre, Nashik
2
 TCP/IP in Java
 Sockets
 Datagrams
Internet
Server
PC client
Local Area Network
PDA
 To take advantage of opportunities presented by the
Internet, businesses are continuously seeking new
and innovative ways and means for offering their
services via the Internet.
 This created a huge demand for software designers
with skills to create new Internet-enabled
applications or migrate existing/legacy applications
on the Internet platform.
 Object-oriented Java technologies—Sockets, threads,
RMI, clustering, Web services-- have emerged as
leading solutions for creating portable, efficient, and
maintainable large and complex Internet
applications.
 The TCP and UDP
protocols use ports to
map incoming data to
a particular process
running on a
computer.
server
P
o
r
t
Client
TCP
TCP or UDP
port port port port
app app app app
port# dataData
Packet
 Port is represented by a positive (16-bit) integer
value
 Some ports have been reserved to support
common/well known services:
 ftp 21/tcp
 telnet 23/tcp
 smtp 25/tcp
 login 513/tcp
 User level process/services generally use port
number value >= 1024
 Sockets provide an interface for programming
networks at the transport layer.
 Network communication using Sockets is very much
similar to performing file I/O
 In fact, socket handle is treated like file handle.
 The streams used in file I/O operation are also applicable to
socket-based I/O
 Socket-based communication is programming
language independent.
 That means, a socket program written in Java language can also
communicate to a program written in Java or non-Java socket
program.
 A server (program) runs on a specific computer
and has a socket that is bound to a specific
port. The server waits and listens to the socket
for a client to make a connection request.
server
Client
Connection request
port
 If everything goes well, the server accepts the
connection. Upon acceptance, the server gets a new
socket bounds to a different port. It needs a new socket
(consequently a different port number) so that it can
continue to listen to the original socket for connection
requests while serving the connected client.
server
Client
Connection
port
port
port
 A connection-based protocol that provides a reliable
flow of data between two computers.
 Provides a point-to-point channel for applications
that require reliable communications.
 The Hypertext Transfer Protocol (HTTP), File Transfer
Protocol (FTP), and Telnet are all examples of applications
that require a reliable communication channel
 Guarantees that data sent from one end of the
connection actually gets to the other end and in the
same order it was sent. Otherwise, an error is
reported.
 A protocol that sends independent packets of
data, called datagrams, from one computer to
another with no guarantees about arrival. UDP is
not connection-based like TCP and is not reliable:
 Sender does not wait for acknowledgements
 Arrival order is not guaranteed
 Arrival is not guaranteed
 Used when speed is essential, even in cost of
reliability
 e.g. streaming media, games, Internet telephony, etc.
 Through the classes in java.net, Java programs
can use TCP or UDP to communicate over the
Internet.
 The URL, URLConnection, Socket, and
ServerSocket classes all use TCP to communicate
over the network.
 The DatagramPacket, DatagramSocket, and
MulticastSocket classes are for use with UDP.
 Accessing TCP/IP from Java is
straightforward. The main functionality is in
the following classes:
 java.net.InetAddress : Represents an IP
address (either IPv4 or IPv6) and has methods for
performing DNS lookup.
 java.net.Socket : Represents a TCP socket.
 java.net.ServerSocket : Represents a server
socket which is capable of waiting for requests from
clients.
14
 A socket is an endpoint of a two-way
communication link between two programs
running on the network.
 A socket is bound to a port number so that the
TCP layer can identify the application that data
destined to be sent.
 Java’s .net package provides two classes:
 Socket – for implementing a client
 ServerSocket – for implementing a server
15
ServerSocket(1234)
Socket(“128.250.25.158”, 1234)
Output/write stream
Input/read stream
It can be host_name like “books.google.com”
Client
Server
16
 Java wraps OS sockets (over TCP) by the
objects of class java.net.Socket
Socket(String remoteHost, int remotePort)
 Creates a TCP socket and connects it to the
remote host on the remote port (hand shake)
 Write and read using streams:
 InputStream getInputStream()
 OutputStream getOutputStream()
 Socket(String remoteHost, int remotePort)
 Socket(InetAddress ip, int remotePort)
 InetAddress getInetAddress( )
 int getPort( )
 int getLocalPort( )
 InputStream getInputStream( )
 OutputStream getOutputStream( )
 void close( )
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
3. Perform I/O or communication with the server:
 Receive data from the server:
String line = is.readLine();
 Send data to the server:
os.writeBytes("Hellon");
4. Close the socket when done:
client.close();
class Whois
{
public static void main(String args[ ]) throws Exception
{
int c;
Socket s = new Socket("internic.net", 43);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
String str="www.google.com";
byte buf[] = str.getBytes();
out.write(buf);
while ((c = in.read()) != -1)
System.out.print((char) c);
s.close();
}
}
public class Daytime
{
public static void main(String[] args) throws Exception
{
Socket theSocket = new Socket("time.nist.gov", 13);
InputStream timeStream = theSocket.getInputStream( );
StringBuffer time = new StringBuffer( );
int c;
while ((c = timeStream.read( )) != -1) time.append((char) c);
String timeString = time.toString( ).trim( );
System.out.println("It is " + timeString + " at " + "local host");
}
}
22
 This class implements server sockets. A server
socket waits for requests to come in over the
network. It performs some operation based on
that request, and then possibly returns a result
to the requester.
 A server socket is technically not a socket:
when a client connects to a server socket, a TCP
connection is made, and a (normal) socket is
created for each end point.
 ServerSocket (int port)
throws BindException, IOException
 ServerSocket (int port, int maxQueue)
throws BindException, IOException
 ServerSocket (int port, int maxQ,
InetAddress ip)
throws IOException
• Open the Server Socket:
ServerSocket server=new ServerSocket(P);;
DataOutputStream os;
DataInputStream is;
• Wait for the Client Request:
Socket client = server.accept();
• Create I/O streams for communicating to the client
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
• Perform communication with client
Receive from client: String line =
is.readLine();
Send to client: os.writeBytes("Hellon");
• Close sockets: client.close();
 Usually, the accept() method is executed
within an infinite loop
 i.e. while(true){...}
 The accept method returns a new socket (with
a new port) for the new channel. It blocks until
connection is made.
 Syntax:
 Socket accept() throws IOException
 EchoDemoServer
 EchoDemoClient
28
 A datagram is an independent, self-contained
message sent over the network whose arrival,
arrival time, and content are not guaranteed.
 The java.net package contains three classes to
help us write Java programs that use
datagrams to send and receive packets over the
network: DatagramSocket and DatagramPacket
No. TCP UDP
1 This Connection oriented protocol This is connection-less protocol
2
The TCP connection is byte stream The UDP connection is a message
stream
3
It does not support multicasting and
broadcasting
It supports broadcasting
4
It provides error control and flow
control
The error control and flow control is
not provided
5
TCP supports full duplex
transmission
UDP does not support full duplex
transmission
6
It is reliable service of data
transmission
This is an unreliable service of data
transmission
7
The TCP packet is called as segment The UDP packet is called as user
datagram.
 DatagramPacket
 DatagramSocket
 public DatagramPacket(byte[ ]
buffer, int length)
 public DatagramPacket(byte[ ]
buffer, int offset, int length)
 Example:
byte[ ] buffer = new byte[8192];
DatagramPacket dp = new
DatagramPacket(buffer, buffer.length);
 public DatagramPacket(byte[ ] data, int length,
InetAddress destination, int port)
 public DatagramPacket(byte[ ] data, int offset,
int length, InetAddress destination, int port)
 public DatagramSocket( ) throws
SocketException
 public DatagramSocket(int port)
throws SocketException
 public DatagramSocket(int port,
InetAddress add)
throws SocketException
 public void send(DatagramPacket dp)
throws IOException
 public void receive(DatagramPacket
dp) throws IOException
 UDPServer
 UDPClient
1. Java Network Programming,
3rd Edition, By Elliotte Rusty Harold, O'Reilly, October 2004
Chapter 2: Basic Networking Concepts
Chapter 7: URLs and URIs
Chapter 9: Sockets for Clients
Chapter 10: Sockets for Servers
Chapter 13: UDP Datagrams and Sockets
Chapter 15: URL Connections
2. Java 2 the Complete Reference,
Fifth Edition by Herbert Schildt, 2001, Osborne McGraw
Hill.
Chapter 18: Networking
Networking in Java

More Related Content

What's hot (20)

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Applets
AppletsApplets
Applets
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Exception handling
Exception handlingException handling
Exception handling
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 

Similar to Networking in Java

Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in JavaTushar B Kute
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
Socket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaSocket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaiDhawalVaja
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptxRoshniSundrani
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Networking
NetworkingNetworking
NetworkingTuan Ngo
 
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriyaIPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriyaVijiPriya Jeyamani
 

Similar to Networking in Java (20)

Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
28 networking
28  networking28  networking
28 networking
 
Sockets
SocketsSockets
Sockets
 
Networking
NetworkingNetworking
Networking
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Socket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaSocket Programming by Rajkumar Buyya
Socket Programming by Rajkumar Buyya
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptx
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
#1 (TCPvs. UDP)
#1 (TCPvs. UDP)#1 (TCPvs. UDP)
#1 (TCPvs. UDP)
 
Lecture25
Lecture25Lecture25
Lecture25
 
NP-lab-manual (1).pdf
NP-lab-manual (1).pdfNP-lab-manual (1).pdf
NP-lab-manual (1).pdf
 
NP-lab-manual.pdf
NP-lab-manual.pdfNP-lab-manual.pdf
NP-lab-manual.pdf
 
NP-lab-manual.docx
NP-lab-manual.docxNP-lab-manual.docx
NP-lab-manual.docx
 
Networking
NetworkingNetworking
Networking
 
Java networking
Java networkingJava networking
Java networking
 
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriyaIPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
 
Java 1
Java 1Java 1
Java 1
 

More from Tushar B Kute

Apache Pig: A big data processor
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processorTushar B Kute
 
01 Introduction to Android
01 Introduction to Android01 Introduction to Android
01 Introduction to AndroidTushar B Kute
 
Ubuntu OS and it's Flavours
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's FlavoursTushar B Kute
 
Install Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteTushar B Kute
 
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteTushar B Kute
 
Share File easily between computers using sftp
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftpTushar B Kute
 
Signal Handling in Linux
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in LinuxTushar B Kute
 
Implementation of FIFO in Linux
Implementation of FIFO in LinuxImplementation of FIFO in Linux
Implementation of FIFO in LinuxTushar B Kute
 
Implementation of Pipe in Linux
Implementation of Pipe in LinuxImplementation of Pipe in Linux
Implementation of Pipe in LinuxTushar B Kute
 
Basic Multithreading using Posix Threads
Basic Multithreading using Posix ThreadsBasic Multithreading using Posix Threads
Basic Multithreading using Posix ThreadsTushar B Kute
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxTushar B Kute
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxTushar B Kute
 
Part 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingTushar B Kute
 
Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Tushar B Kute
 
Open source applications softwares
Open source applications softwaresOpen source applications softwares
Open source applications softwaresTushar B Kute
 
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Tushar B Kute
 
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteTushar B Kute
 
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrcTechnical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrcTushar B Kute
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 

More from Tushar B Kute (20)

Apache Pig: A big data processor
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processor
 
01 Introduction to Android
01 Introduction to Android01 Introduction to Android
01 Introduction to Android
 
Ubuntu OS and it's Flavours
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's Flavours
 
Install Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. Kute
 
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. Kute
 
Share File easily between computers using sftp
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftp
 
Signal Handling in Linux
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in Linux
 
Implementation of FIFO in Linux
Implementation of FIFO in LinuxImplementation of FIFO in Linux
Implementation of FIFO in Linux
 
Implementation of Pipe in Linux
Implementation of Pipe in LinuxImplementation of Pipe in Linux
Implementation of Pipe in Linux
 
Basic Multithreading using Posix Threads
Basic Multithreading using Posix ThreadsBasic Multithreading using Posix Threads
Basic Multithreading using Posix Threads
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
 
Part 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module Programming
 
Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)
 
Open source applications softwares
Open source applications softwaresOpen source applications softwares
Open source applications softwares
 
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
 
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
 
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrcTechnical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrc
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 

Recently uploaded

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 

Recently uploaded (20)

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

Networking in Java

  • 1. Tushar B Kute, Assistant Professor, Sandip Institute of Technology & Research Centre, Nashik
  • 2. 2  TCP/IP in Java  Sockets  Datagrams
  • 4.  To take advantage of opportunities presented by the Internet, businesses are continuously seeking new and innovative ways and means for offering their services via the Internet.  This created a huge demand for software designers with skills to create new Internet-enabled applications or migrate existing/legacy applications on the Internet platform.  Object-oriented Java technologies—Sockets, threads, RMI, clustering, Web services-- have emerged as leading solutions for creating portable, efficient, and maintainable large and complex Internet applications.
  • 5.  The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. server P o r t Client TCP TCP or UDP port port port port app app app app port# dataData Packet
  • 6.  Port is represented by a positive (16-bit) integer value  Some ports have been reserved to support common/well known services:  ftp 21/tcp  telnet 23/tcp  smtp 25/tcp  login 513/tcp  User level process/services generally use port number value >= 1024
  • 7.  Sockets provide an interface for programming networks at the transport layer.  Network communication using Sockets is very much similar to performing file I/O  In fact, socket handle is treated like file handle.  The streams used in file I/O operation are also applicable to socket-based I/O  Socket-based communication is programming language independent.  That means, a socket program written in Java language can also communicate to a program written in Java or non-Java socket program.
  • 8.  A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request. server Client Connection request port
  • 9.  If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client. server Client Connection port port port
  • 10.  A connection-based protocol that provides a reliable flow of data between two computers.  Provides a point-to-point channel for applications that require reliable communications.  The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel  Guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent. Otherwise, an error is reported.
  • 11.  A protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP and is not reliable:  Sender does not wait for acknowledgements  Arrival order is not guaranteed  Arrival is not guaranteed  Used when speed is essential, even in cost of reliability  e.g. streaming media, games, Internet telephony, etc.
  • 12.  Through the classes in java.net, Java programs can use TCP or UDP to communicate over the Internet.  The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate over the network.  The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with UDP.
  • 13.  Accessing TCP/IP from Java is straightforward. The main functionality is in the following classes:  java.net.InetAddress : Represents an IP address (either IPv4 or IPv6) and has methods for performing DNS lookup.  java.net.Socket : Represents a TCP socket.  java.net.ServerSocket : Represents a server socket which is capable of waiting for requests from clients.
  • 14. 14  A socket is an endpoint of a two-way communication link between two programs running on the network.  A socket is bound to a port number so that the TCP layer can identify the application that data destined to be sent.  Java’s .net package provides two classes:  Socket – for implementing a client  ServerSocket – for implementing a server
  • 15. 15 ServerSocket(1234) Socket(“128.250.25.158”, 1234) Output/write stream Input/read stream It can be host_name like “books.google.com” Client Server
  • 16. 16  Java wraps OS sockets (over TCP) by the objects of class java.net.Socket Socket(String remoteHost, int remotePort)  Creates a TCP socket and connects it to the remote host on the remote port (hand shake)  Write and read using streams:  InputStream getInputStream()  OutputStream getOutputStream()
  • 17.  Socket(String remoteHost, int remotePort)  Socket(InetAddress ip, int remotePort)
  • 18.  InetAddress getInetAddress( )  int getPort( )  int getLocalPort( )  InputStream getInputStream( )  OutputStream getOutputStream( )  void close( )
  • 19. 1. Create a Socket Object: client = new Socket( server, port_id ); 2. Create I/O streams for communicating with the server. is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 3. Perform I/O or communication with the server:  Receive data from the server: String line = is.readLine();  Send data to the server: os.writeBytes("Hellon"); 4. Close the socket when done: client.close();
  • 20. class Whois { public static void main(String args[ ]) throws Exception { int c; Socket s = new Socket("internic.net", 43); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); String str="www.google.com"; byte buf[] = str.getBytes(); out.write(buf); while ((c = in.read()) != -1) System.out.print((char) c); s.close(); } }
  • 21. public class Daytime { public static void main(String[] args) throws Exception { Socket theSocket = new Socket("time.nist.gov", 13); InputStream timeStream = theSocket.getInputStream( ); StringBuffer time = new StringBuffer( ); int c; while ((c = timeStream.read( )) != -1) time.append((char) c); String timeString = time.toString( ).trim( ); System.out.println("It is " + timeString + " at " + "local host"); } }
  • 22. 22  This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.  A server socket is technically not a socket: when a client connects to a server socket, a TCP connection is made, and a (normal) socket is created for each end point.
  • 23.  ServerSocket (int port) throws BindException, IOException  ServerSocket (int port, int maxQueue) throws BindException, IOException  ServerSocket (int port, int maxQ, InetAddress ip) throws IOException
  • 24. • Open the Server Socket: ServerSocket server=new ServerSocket(P);; DataOutputStream os; DataInputStream is; • Wait for the Client Request: Socket client = server.accept(); • Create I/O streams for communicating to the client is = new DataInputStream(client.getInputStream()); os = new DataOutputStream(client.getOutputStream()); • Perform communication with client Receive from client: String line = is.readLine(); Send to client: os.writeBytes("Hellon"); • Close sockets: client.close();
  • 25.  Usually, the accept() method is executed within an infinite loop  i.e. while(true){...}  The accept method returns a new socket (with a new port) for the new channel. It blocks until connection is made.  Syntax:  Socket accept() throws IOException
  • 26.
  • 28. 28  A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.  The java.net package contains three classes to help us write Java programs that use datagrams to send and receive packets over the network: DatagramSocket and DatagramPacket
  • 29. No. TCP UDP 1 This Connection oriented protocol This is connection-less protocol 2 The TCP connection is byte stream The UDP connection is a message stream 3 It does not support multicasting and broadcasting It supports broadcasting 4 It provides error control and flow control The error control and flow control is not provided 5 TCP supports full duplex transmission UDP does not support full duplex transmission 6 It is reliable service of data transmission This is an unreliable service of data transmission 7 The TCP packet is called as segment The UDP packet is called as user datagram.
  • 31.  public DatagramPacket(byte[ ] buffer, int length)  public DatagramPacket(byte[ ] buffer, int offset, int length)  Example: byte[ ] buffer = new byte[8192]; DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
  • 32.  public DatagramPacket(byte[ ] data, int length, InetAddress destination, int port)  public DatagramPacket(byte[ ] data, int offset, int length, InetAddress destination, int port)
  • 33.  public DatagramSocket( ) throws SocketException  public DatagramSocket(int port) throws SocketException  public DatagramSocket(int port, InetAddress add) throws SocketException
  • 34.  public void send(DatagramPacket dp) throws IOException  public void receive(DatagramPacket dp) throws IOException
  • 36. 1. Java Network Programming, 3rd Edition, By Elliotte Rusty Harold, O'Reilly, October 2004 Chapter 2: Basic Networking Concepts Chapter 7: URLs and URIs Chapter 9: Sockets for Clients Chapter 10: Sockets for Servers Chapter 13: UDP Datagrams and Sockets Chapter 15: URL Connections 2. Java 2 the Complete Reference, Fifth Edition by Herbert Schildt, 2001, Osborne McGraw Hill. Chapter 18: Networking