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

Mais conteúdo relacionado

Mais procurados (20)

Java Programming - 07 java networking
Java Programming - 07 java networkingJava Programming - 07 java networking
Java Programming - 07 java networking
 
Java networking
Java networkingJava networking
Java networking
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket based
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
Java API: java.net.InetAddress
Java API: java.net.InetAddressJava API: java.net.InetAddress
Java API: java.net.InetAddress
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
Chap 1 Network Theory & Java Overview
Chap 1   Network Theory & Java OverviewChap 1   Network Theory & Java Overview
Chap 1 Network Theory & Java Overview
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
Ipc
IpcIpc
Ipc
 
Python networking
Python networkingPython networking
Python networking
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
 
Module 1 networking basics-2
Module 1   networking basics-2Module 1   networking basics-2
Module 1 networking basics-2
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programming
 

Destaque

Introduction of reflection
Introduction of reflection Introduction of reflection
Introduction of reflection Ravindra Rathore
 
Ch11 communication
Ch11  communicationCh11  communication
Ch11 communicationadrienne0901
 
Lecture 5 phasor notations
Lecture 5 phasor notationsLecture 5 phasor notations
Lecture 5 phasor notationsRavindra Rathore
 
Spread spectrum
Spread spectrumSpread spectrum
Spread spectrumRina Ahire
 
T com presentation (error correcting code)
T com presentation   (error correcting code)T com presentation   (error correcting code)
T com presentation (error correcting code)Akshit Jain
 
Low noise amplifier csd
Low noise amplifier csdLow noise amplifier csd
Low noise amplifier csdRina Ahire
 
Digital Communication 2
Digital Communication 2Digital Communication 2
Digital Communication 2admercano101
 
Digital Communication 4
Digital Communication 4Digital Communication 4
Digital Communication 4admercano101
 
Analytic geometry lecture2
Analytic geometry lecture2Analytic geometry lecture2
Analytic geometry lecture2admercano101
 
Data Communication 1
Data Communication 1Data Communication 1
Data Communication 1admercano101
 

Destaque (20)

26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
 
Introduction of reflection
Introduction of reflection Introduction of reflection
Introduction of reflection
 
Ch11 communication
Ch11  communicationCh11  communication
Ch11 communication
 
Lecture 5 phasor notations
Lecture 5 phasor notationsLecture 5 phasor notations
Lecture 5 phasor notations
 
21 multi threading - iii
21 multi threading - iii21 multi threading - iii
21 multi threading - iii
 
22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 
Vlsi
VlsiVlsi
Vlsi
 
Fiber optics101
Fiber optics101Fiber optics101
Fiber optics101
 
Spread spectrum
Spread spectrumSpread spectrum
Spread spectrum
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
T com presentation (error correcting code)
T com presentation   (error correcting code)T com presentation   (error correcting code)
T com presentation (error correcting code)
 
Low noise amplifier csd
Low noise amplifier csdLow noise amplifier csd
Low noise amplifier csd
 
Digital Communication 2
Digital Communication 2Digital Communication 2
Digital Communication 2
 
Line coding
Line codingLine coding
Line coding
 
Digital Communication 4
Digital Communication 4Digital Communication 4
Digital Communication 4
 
Limits
LimitsLimits
Limits
 
Trigonometry101
Trigonometry101Trigonometry101
Trigonometry101
 
Analytic geometry lecture2
Analytic geometry lecture2Analytic geometry lecture2
Analytic geometry lecture2
 
Data Communication 1
Data Communication 1Data Communication 1
Data Communication 1
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
 

Semelhante a 28 networking

5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptxEliasPetros
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationPiyush Rawat
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
15network Programming Clients
15network Programming Clients15network Programming Clients
15network Programming ClientsAdil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project ReportKavita Sharma
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptxRoshniSundrani
 
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
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 

Semelhante a 28 networking (20)

5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Sockets
SocketsSockets
Sockets
 
A.java
A.javaA.java
A.java
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
Networking
NetworkingNetworking
Networking
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
15network Programming Clients
15network Programming Clients15network Programming Clients
15network Programming Clients
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptx
 
Multi user chat system using java
Multi user chat system using javaMulti user chat system using java
Multi user chat system using java
 
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
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
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
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Java 1
Java 1Java 1
Java 1
 
NP-lab-manual.docx
NP-lab-manual.docxNP-lab-manual.docx
NP-lab-manual.docx
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
 

Último

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Último (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

28 networking

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