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

More Related Content

What's hot

Java Programming - 07 java networking
Java Programming - 07 java networkingJava Programming - 07 java networking
Java Programming - 07 java networking
Danairat Thanabodithammachari
 
Java networking
Java networkingJava networking
Java networking
Arati Gadgil
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
CEC Landran
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket based
Mukesh Tekwani
 
Java API: java.net.InetAddress
Java API: java.net.InetAddressJava API: java.net.InetAddress
Java API: java.net.InetAddress
Sayak Sarkar
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)UC San Diego
 
Chap 1 Network Theory & Java Overview
Chap 1   Network Theory & Java OverviewChap 1   Network Theory & Java Overview
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
Tushar B Kute
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
Gera Paulos
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
suraj pandey
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Module 1 networking basics-2
Module 1   networking basics-2Module 1   networking basics-2
Module 1 networking basics-2
Ankit Dubey
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programming
Mmanan91
 

What's hot (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
 

Viewers also liked

Introduction of reflection
Introduction of reflection Introduction of reflection
Introduction of reflection
Ravindra Rathore
 
Ch11 communication
Ch11  communicationCh11  communication
Ch11 communication
adrienne0901
 
Lecture 5 phasor notations
Lecture 5 phasor notationsLecture 5 phasor notations
Lecture 5 phasor notations
Ravindra Rathore
 
Fiber optics101
Fiber optics101Fiber optics101
Fiber optics101
admercano101
 
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 2
admercano101
 
Line coding
Line codingLine coding
Line coding
Gagan Randhawa
 
Digital Communication 4
Digital Communication 4Digital Communication 4
Digital Communication 4
admercano101
 
Limits
LimitsLimits
Limits
admercano101
 
Trigonometry101
Trigonometry101Trigonometry101
Trigonometry101
admercano101
 
Analytic geometry lecture2
Analytic geometry lecture2Analytic geometry lecture2
Analytic geometry lecture2
admercano101
 
Data Communication 1
Data Communication 1Data Communication 1
Data Communication 1
admercano101
 

Viewers also liked (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
 

Similar to 28 networking

5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
EliasPetros
 
A.java
A.javaA.java
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
Piyush Rawat
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal 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.pptx
RoshniSundrani
 
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
VijiPriya Jeyamani
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
phanleson
 
NP-lab-manual (1).pdf
NP-lab-manual (1).pdfNP-lab-manual (1).pdf
NP-lab-manual (1).pdf
RaviRajput416403
 
NP-lab-manual.pdf
NP-lab-manual.pdfNP-lab-manual.pdf
NP-lab-manual.pdf
RaviRajput416403
 
Socket programming
Socket programmingSocket programming
Socket programming
Padmavathione
 
Java 1
Java 1Java 1
NP-lab-manual.docx
NP-lab-manual.docxNP-lab-manual.docx
NP-lab-manual.docx
RaviRajput416403
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
Hemant Chetwani
 

Similar to 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
 

Recently uploaded

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 

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(); } }