SlideShare a Scribd company logo
1 of 30
Download to read offline
Networking
Shravan Upadhayay
Shravan Upadhay
Introduction
 Java.net package provides support
for networking.
 What makes Java a good language
for networking are the classes defined
in the java.net package.
Shravan Upadhay
Concept of Networking
Shravan Upadhay
Sockets
 Socket is the name given , in one
particular programming model, to the
end points of a communication link
between processes.
 When processes communicate over a
network, Java Technology uses
streams model.
Shravan Upadhay
Sockets
 Sockets:
 Sockets hold two streams: an input
stream and an output stream.
 Each end of the socket has a pair of
streams.
Shravan Upadhay
Socket
 A process send data to another process
through a network by writing to the
output stream associated with the
Socket.
 A process reads data written by another
process by reading from the input
stream associated with the Socket.
Shravan Upadhay
Setting Up the Connection
 To setup the network connection, one
machine must run a program that is
waiting for a connection, and a
second machine must try to reach the
first.
 Set up of a network connection is
similar to a telephone system: One
end must dial the other end, which
must be listening.
Shravan Upadhay
Networking
Shravan Upadhay
Addressing the Connection
 When you make a network connection,
you need to know the address or the
name of the remote machine.
 In addition, a network connection,
requires a port number, which you can
think of as a telephone extension
number.
Shravan Upadhay
Port Numbers
 Port numbers in TCP/IP systems are
16-bit numbers and the values range
from 0-65535.
 Port numbers below 1024 are reserved
for predefined services.
 Client port numbers are allocated by the
host OS to something not in use, while
server port numbers are specified by the
programmer, and are used to identify a
particular service.
Shravan Upadhay
 Both client and server must agree in
advance on which port to use.
 If the port numbers used by the two
parts of the system do not agree,
communication does not occur.
Shravan Upadhay
Server
 A server is anything that has some
resource that can be shared.
 There are compute servers, which
provide computing power;
 print servers, which manage a collection
of printers;
 disk servers, which provide networked
disk space;
 and web servers, which store web pages.
Shravan Upadhay
Client
 A client is simply any other entity
that wants to gain access to a
particular server.
Shravan Upadhay
 The notion of a socket allows a single computer to
serve many different clients at once, as well as
serving many different types of information.
 This feat is managed by the introduction 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. A server is allowed to accept
multiple clients connected to the same port number,
although each session is unique.
 To manage multiple client connections, a server
process must be multithreaded or have some other
means of multiplexing the simultaneous I/O.
Shravan Upadhay
Local Host Info
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws
UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address.getHostName());
System.out.println(Address.getHostAddress());
}
}
Shravan Upadhay
TCP/IP
 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.
Shravan Upadhay
 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.
 The Socket class is designed to connect to
server sockets and initiate protocol
exchanges.
Shravan Upadhay
 The creation of a Socket object
implicitly establishes a connection
between the client and server.
 There are no methods or constructors
that explicitly expose the details of
establishing that connection.
Shravan Upadhay
 Here are two constructors used to create
client sockets:
 Socket(String hostName, int port)
 Creates a socket connecting the local host to the
named host and port; can throw an
UnknownHostException or an IOException.
 Socket(InetAddress ipAddress, int port)
 Creates a socket using a preexisting
InetAddress object and a port; can throw an
IOException.
Shravan Upadhay
 A socket can be examined at any time for
the address and port information
associated with it, by use of the following
methods:
 InetAddress getInetAddress( )
 Returns the InetAddress associated with
the Socket object.
 int getPort( )
 Returns the remote port to which this
Socket object is connected.
 int getLocalPort( )
 Returns the local port to which this Socket
object is connected.
Shravan Upadhay
 Once the Socket object has been created,
it can also be examined to gain access to
the input and output streams associated
with it.
 Each of these methods can throw an
IOException if the sockets have been
invalidated by a loss of connection on the
Net.
 These streams are used exactly like the I/O
streams receive data.
 InputStream getInputStream( )
 Returns the InputStream
Shravan Upadhay
 InputStream getInputStream( )
 Returns the InputStream associated
with the invoking socket.
 OutputStream getOutputStream()
 Returns the OutputStream
associated with the invoking socket.
 void close()
 Closes both the InputStream and
OutputStream.
Shravan Upadhay
Socket functional calls
 socket (): Create a socket
 bind(): bind a socket to a local IP address and port #
 listen(): passively waiting for connections
 connect(): initiating connection to another socket
 accept(): accept a new connection
 Write(): write data to a socket
 Read(): read data from a socket
 close(): close a socket (tear down the connection)
Shravan Upadhay
Socket-programming using TCP
TCP service: reliable byte stream transfer
process
TCP with
buffers,
variables
socket
controlled by
application
developer
controlled by
operating
system
process
TCP with
buffers,
variables
socket
internet
client
serversocket( )
bind( )
connect( )
socket( )
bind( )
listen( )
accept( )
send( )
recv( )
close( ) close( )
recv( )
send( )
TCP conn. request
TCP ACK
Shravan Upadhay
Socket programming with TCP
Example client-server app:
 client reads line from standard
input (inFromUser stream) ,
sends to server via socket
(outToServer stream)
 server reads line from socket
 server converts line to
uppercase, sends back to
client
 client reads, prints modified
line from socket
(inFromServer stream)
outToServer
tonetwork fromnetwork
inFromServer
inFromUser
keyboard monitor
Process
clientSocket
input
stream
input
stream
output
stream
TCP
socket
Input stream:
sequence of bytes
into processoutput stream:
sequence of bytes
out of process
Client
process
client TCP
socket
Shravan Upadhay
Client/server socket interaction: TCP
wait for incoming
connection request
connectionSocket =
welcomeSocket.accept()
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
create socket,
connect to hostid, port=x
clientSocket =
Socket()
close
connectionSocket
read reply from
clientSocket
close
clientSocket
Server (running on hostid) Client
send request using
clientSocketread request from
connectionSocket
write reply to
connectionSocket
TCP
connection setup
Shravan Upadhay
TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
        String sentence;
        String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
       
DataOutputStream outToServer =
         new DataOutputStream(clientSocket.getOutputStream());
Shravan Upadhay
TCPClient.java
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();
                  
}
}
Shravan Upadhay
TCPServer.java
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()));
Shravan Upadhay
TCPServer.java
           DataOutputStream  outToClient =
             new DataOutputStream(connectionSocket.getOutputStream());
          
clientSentence = inFromClient.readLine();
          
capitalizedSentence = clientSentence.toUpperCase() + 'n';
outToClient.writeBytes(capitalizedSentence);
       
}
}
}

More Related Content

What's hot

Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programmingashok hirpara
 
Java Network Programming
Java Network ProgrammingJava Network Programming
Java Network Programmingbackdoor
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket basedMukesh Tekwani
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)UC San Diego
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In JavaAnkur Agrawal
 
A Short Java Socket Tutorial
A Short Java Socket TutorialA Short Java Socket Tutorial
A Short Java Socket TutorialGuo Albert
 
Java API: java.net.InetAddress
Java API: java.net.InetAddressJava API: java.net.InetAddress
Java API: java.net.InetAddressSayak Sarkar
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket ProgrammingVipin Yadav
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Multiplayer Java Game
Multiplayer Java GameMultiplayer Java Game
Multiplayer Java Gamekarim baidar
 

What's hot (20)

Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Java Network Programming
Java Network ProgrammingJava Network Programming
Java Network Programming
 
Java networking
Java networkingJava networking
Java networking
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket based
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 
A Short Java Socket Tutorial
A Short Java Socket TutorialA Short Java Socket Tutorial
A Short Java Socket Tutorial
 
Java API: java.net.InetAddress
Java API: java.net.InetAddressJava API: java.net.InetAddress
Java API: java.net.InetAddress
 
Java sockets
Java socketsJava sockets
Java sockets
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Multiplayer Java Game
Multiplayer Java GameMultiplayer Java Game
Multiplayer Java Game
 
Sockets
SocketsSockets
Sockets
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Socket programming
Socket programmingSocket programming
Socket programming
 

Viewers also liked

Java ME Networking & Connectivity
Java ME Networking & ConnectivityJava ME Networking & Connectivity
Java ME Networking & ConnectivityStefano Sanna
 
Stop guessing - make cashless payments a success
Stop guessing - make cashless payments a successStop guessing - make cashless payments a success
Stop guessing - make cashless payments a successBSGAfrica
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewCraig Dickson
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
Geometric transformation 2d chapter 5
Geometric transformation 2d   chapter 5Geometric transformation 2d   chapter 5
Geometric transformation 2d chapter 5geethawilliam
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
2 d transformations by amit kumar (maimt)
2 d transformations by amit kumar (maimt)2 d transformations by amit kumar (maimt)
2 d transformations by amit kumar (maimt)Amit Kapoor
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8Simon Ritter
 

Viewers also liked (19)

Java ME Networking & Connectivity
Java ME Networking & ConnectivityJava ME Networking & Connectivity
Java ME Networking & Connectivity
 
Stop guessing - make cashless payments a success
Stop guessing - make cashless payments a successStop guessing - make cashless payments a success
Stop guessing - make cashless payments a success
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Geometric transformation 2d chapter 5
Geometric transformation 2d   chapter 5Geometric transformation 2d   chapter 5
Geometric transformation 2d chapter 5
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
2 d transformations by amit kumar (maimt)
2 d transformations by amit kumar (maimt)2 d transformations by amit kumar (maimt)
2 d transformations by amit kumar (maimt)
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 

Similar to Networking in java

Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in JavaTushar B Kute
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptxRoshniSundrani
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project ReportKavita Sharma
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Javasuraj pandey
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptxEliasPetros
 
Lan chat system
Lan chat systemLan chat system
Lan chat systemWipro
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programmingGera Paulos
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAMaulik Borsaniya
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded wsmile790243
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationSamsil Arefin
 
Networking
NetworkingNetworking
NetworkingTuan Ngo
 

Similar to Networking in java (20)

Java 1
Java 1Java 1
Java 1
 
Socket
SocketSocket
Socket
 
Lecture25
Lecture25Lecture25
Lecture25
 
Client server project
Client server projectClient server project
Client server project
 
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
 
A.java
A.javaA.java
A.java
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptx
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
 
17-Networking.pdf
17-Networking.pdf17-Networking.pdf
17-Networking.pdf
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
Lan chat system
Lan chat systemLan chat system
Lan chat system
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
 
Multi user chat system using java
Multi user chat system using javaMulti user chat system using java
Multi user chat system using java
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
Networking
NetworkingNetworking
Networking
 

Recently uploaded

3.19.24 Urban Uprisings and the Chicago Freedom Movement.pptx
3.19.24 Urban Uprisings and the Chicago Freedom Movement.pptx3.19.24 Urban Uprisings and the Chicago Freedom Movement.pptx
3.19.24 Urban Uprisings and the Chicago Freedom Movement.pptxmary850239
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxMYDA ANGELICA SUAN
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17Celine George
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxEduSkills OECD
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfYu Kanazawa / Osaka University
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational PhilosophyShuvankar Madhu
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxKatherine Villaluna
 
How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17Celine George
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptxraviapr7
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17Celine George
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 
Latin American Revolutions, c. 1789-1830
Latin American Revolutions, c. 1789-1830Latin American Revolutions, c. 1789-1830
Latin American Revolutions, c. 1789-1830Dave Phillips
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice documentXsasf Sfdfasd
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationMJDuyan
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxraviapr7
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17Celine George
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfTechSoup
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?TechSoup
 

Recently uploaded (20)

3.19.24 Urban Uprisings and the Chicago Freedom Movement.pptx
3.19.24 Urban Uprisings and the Chicago Freedom Movement.pptx3.19.24 Urban Uprisings and the Chicago Freedom Movement.pptx
3.19.24 Urban Uprisings and the Chicago Freedom Movement.pptx
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptx
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational Philosophy
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
 
How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 
Latin American Revolutions, c. 1789-1830
Latin American Revolutions, c. 1789-1830Latin American Revolutions, c. 1789-1830
Latin American Revolutions, c. 1789-1830
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice document
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive Education
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptx
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?
 
Prelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quizPrelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quiz
 

Networking in java

  • 2. Shravan Upadhay Introduction  Java.net package provides support for networking.  What makes Java a good language for networking are the classes defined in the java.net package.
  • 4. Shravan Upadhay Sockets  Socket is the name given , in one particular programming model, to the end points of a communication link between processes.  When processes communicate over a network, Java Technology uses streams model.
  • 5. Shravan Upadhay Sockets  Sockets:  Sockets hold two streams: an input stream and an output stream.  Each end of the socket has a pair of streams.
  • 6. Shravan Upadhay Socket  A process send data to another process through a network by writing to the output stream associated with the Socket.  A process reads data written by another process by reading from the input stream associated with the Socket.
  • 7. Shravan Upadhay Setting Up the Connection  To setup the network connection, one machine must run a program that is waiting for a connection, and a second machine must try to reach the first.  Set up of a network connection is similar to a telephone system: One end must dial the other end, which must be listening.
  • 9. Shravan Upadhay Addressing the Connection  When you make a network connection, you need to know the address or the name of the remote machine.  In addition, a network connection, requires a port number, which you can think of as a telephone extension number.
  • 10. Shravan Upadhay Port Numbers  Port numbers in TCP/IP systems are 16-bit numbers and the values range from 0-65535.  Port numbers below 1024 are reserved for predefined services.  Client port numbers are allocated by the host OS to something not in use, while server port numbers are specified by the programmer, and are used to identify a particular service.
  • 11. Shravan Upadhay  Both client and server must agree in advance on which port to use.  If the port numbers used by the two parts of the system do not agree, communication does not occur.
  • 12. Shravan Upadhay Server  A server is anything that has some resource that can be shared.  There are compute servers, which provide computing power;  print servers, which manage a collection of printers;  disk servers, which provide networked disk space;  and web servers, which store web pages.
  • 13. Shravan Upadhay Client  A client is simply any other entity that wants to gain access to a particular server.
  • 14. Shravan Upadhay  The notion of a socket allows a single computer to serve many different clients at once, as well as serving many different types of information.  This feat is managed by the introduction 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. A server is allowed to accept multiple clients connected to the same port number, although each session is unique.  To manage multiple client connections, a server process must be multithreaded or have some other means of multiplexing the simultaneous I/O.
  • 15. Shravan Upadhay Local Host Info // Demonstrate InetAddress. import java.net.*; class InetAddressTest { public static void main(String args[]) throws UnknownHostException { InetAddress Address = InetAddress.getLocalHost(); System.out.println(Address.getHostName()); System.out.println(Address.getHostAddress()); } }
  • 16. Shravan Upadhay TCP/IP  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.
  • 17. Shravan Upadhay  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.  The Socket class is designed to connect to server sockets and initiate protocol exchanges.
  • 18. Shravan Upadhay  The creation of a Socket object implicitly establishes a connection between the client and server.  There are no methods or constructors that explicitly expose the details of establishing that connection.
  • 19. Shravan Upadhay  Here are two constructors used to create client sockets:  Socket(String hostName, int port)  Creates a socket connecting the local host to the named host and port; can throw an UnknownHostException or an IOException.  Socket(InetAddress ipAddress, int port)  Creates a socket using a preexisting InetAddress object and a port; can throw an IOException.
  • 20. Shravan Upadhay  A socket can be examined at any time for the address and port information associated with it, by use of the following methods:  InetAddress getInetAddress( )  Returns the InetAddress associated with the Socket object.  int getPort( )  Returns the remote port to which this Socket object is connected.  int getLocalPort( )  Returns the local port to which this Socket object is connected.
  • 21. Shravan Upadhay  Once the Socket object has been created, it can also be examined to gain access to the input and output streams associated with it.  Each of these methods can throw an IOException if the sockets have been invalidated by a loss of connection on the Net.  These streams are used exactly like the I/O streams receive data.  InputStream getInputStream( )  Returns the InputStream
  • 22. Shravan Upadhay  InputStream getInputStream( )  Returns the InputStream associated with the invoking socket.  OutputStream getOutputStream()  Returns the OutputStream associated with the invoking socket.  void close()  Closes both the InputStream and OutputStream.
  • 23. Shravan Upadhay Socket functional calls  socket (): Create a socket  bind(): bind a socket to a local IP address and port #  listen(): passively waiting for connections  connect(): initiating connection to another socket  accept(): accept a new connection  Write(): write data to a socket  Read(): read data from a socket  close(): close a socket (tear down the connection)
  • 24. Shravan Upadhay Socket-programming using TCP TCP service: reliable byte stream transfer process TCP with buffers, variables socket controlled by application developer controlled by operating system process TCP with buffers, variables socket internet client serversocket( ) bind( ) connect( ) socket( ) bind( ) listen( ) accept( ) send( ) recv( ) close( ) close( ) recv( ) send( ) TCP conn. request TCP ACK
  • 25. Shravan Upadhay Socket programming with TCP Example client-server app:  client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer stream)  server reads line from socket  server converts line to uppercase, sends back to client  client reads, prints modified line from socket (inFromServer stream) outToServer tonetwork fromnetwork inFromServer inFromUser keyboard monitor Process clientSocket input stream input stream output stream TCP socket Input stream: sequence of bytes into processoutput stream: sequence of bytes out of process Client process client TCP socket
  • 26. Shravan Upadhay Client/server socket interaction: TCP wait for incoming connection request connectionSocket = welcomeSocket.accept() create socket, port=x, for incoming request: welcomeSocket = ServerSocket() create socket, connect to hostid, port=x clientSocket = Socket() close connectionSocket read reply from clientSocket close clientSocket Server (running on hostid) Client send request using clientSocketread request from connectionSocket write reply to connectionSocket TCP connection setup
  • 27. Shravan Upadhay TCPClient.java import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception {         String sentence;         String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789);         DataOutputStream outToServer =          new DataOutputStream(clientSocket.getOutputStream());
  • 28. Shravan Upadhay TCPClient.java 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();                    } }
  • 29. Shravan Upadhay TCPServer.java 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()));
  • 30. Shravan Upadhay TCPServer.java            DataOutputStream  outToClient =              new DataOutputStream(connectionSocket.getOutputStream());            clientSentence = inFromClient.readLine();            capitalizedSentence = clientSentence.toUpperCase() + 'n'; outToClient.writeBytes(capitalizedSentence);         } } }