SlideShare uma empresa Scribd logo
1 de 63
Networking
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Java Networking
 Java Networking is a concept of connecting two or more
computing devices together so that we can share
resources.
 Java socket programming provides facility to share data
between different computing devices.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Socket overview
 A socket is one endpoint of a two-way communication
link between two programs running on the network. A
socket is bound to a port number so that the TCP layer
can identify the application that data is destined to be
sent to.
 An endpoint is a combination of an IP address and a port
number. Every TCP connection can be uniquely identified
by its two endpoints. That way you can have multiple
connections between your host and the server.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 The java.net package in the Java platform provides a
class, Socket, that implements one side of a two-way
connection between your Java program and another
program on the network. The Socket class sits on
top of a platform-dependent implementation, hiding
the details of any particular system from your Java
program. By using the java.net.Socket class instead
of relying on native code, your Java programs can
communicate over the network in a platform-
independent fashion.
 Additionally, java.net includes the ServerSocket class,
which implements a socket that servers can use to
listen for and accept connections to clients.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 The java.net.Socket class represents a socket, and the
java.net.ServerSocket class provides a mechanism for
the server program to listen for clients and establish
connections with them.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 The following steps occur when establishing a TCP
connection between two computers using sockets:
1. The server instantiates a ServerSocket object,
denoting which port number communication is to
occur on.
2. The server invokes the accept() method of the
ServerSocket class. This method waits until a client
connects to the server on the given port.
3. After the server is waiting, a client instantiates a
Socket object, specifying the server name and port
number to connect to.
4. The constructor of the Socket class attempts to
connect the client to the specified server and port
number. If communication is established, the client
now has a Socket object capable of communicating
with the server.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
5. On the server side, the accept() method returns a
reference to a new socket on the server that is
connected to the client's socket.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Internet addressing
 Devices connected to the Internet are called nodes.
Nodes that are computers are called hosts. Each node or
host is identified by at least one unique number called an
Internet address or an IP address. Most current IP
addresses are 4-byte-long IPv4 addresses. However, a
small but growing number of IP addresses are 16-byte-
long IPv6 addresses. (4 and 6 refer to the version of the
Internet Protocol, not the number of the bytes in the
address.) Both IPv4 and IPv6 addresses are ordered
sequences of bytes, like an array. They aren’t numbers,
and they aren’t ordered in any predictable or useful
sense.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 An IPv4 address is normally written as four unsigned
bytes, each ranging from 0 to 255, with the most
significant byte first. Bytes are separated by periods
for the convenience of human eyes. For example, the
address for login.ibiblio.orgis 152.19.134.132. This is
called the dotted quad format.
 An IPv6 address is normally written as eight blocks
of four hexadecimal digits separated by colons. For
example, at the time of this writing, the address
ofwww.hamiltonweather.tk is 2400:cb00:2048:0001:00
00:0000:6ca2:c665. Leading zeros do not need to be
written.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
The InetAddress Class
 The java.net.InetAddress class is Java’s high-level
representation of an IP address, both IPv4 and IPv6. It is
used by most of the other networking classes,
including Socket, ServerSocket, URL, DatagramSocket, D
atagramPacket, and more. Usually, it includes both a
hostname and an IP address.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Creating New InetAddress Objects
 There are no public constructors in
the InetAddress class. Instead,InetAddress has static
factory methods that connect to a DNS server to resolve
a hostname. The most common
is InetAddress.getByName(). For example, this is
how you look up www.oreilly.com:
 InetAddress address =
InetAddress.getByName("www.oreilly.com");
BY LECTURER SURAJ PANDEY CCT
COLLEGE
import java.net.*;
public class OReillyByName {
public static void main (String[] args) {
try {
InetAddress address =
InetAddress.getByName("www.oreilly.com");
System.out.println(address);
} catch (UnknownHostException ex) {
System.out.println("Could not find www.oreilly.com");
}
}
}
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 % java OReillyByName
www.oreilly.com/208.201.239.36
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 You can also do a reverse lookup by IP address. For
example, if you want the hostname for the address
208.201.239.100, pass the dotted quad address to
InetAddress.getByName():
 InetAddress address =
InetAddress.getByName("208.201.239.100");
System.out.println(address.getHostName());If the address
you look up does not have a
hostname, getHostName() simply returns the dotted
quad address you supplied.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
  www.oreilly.com actually has two addresses. Which
one getHostName() returns is indeterminate. If, for some
reason, you need all the addresses of a host,
call getAllByName() instead, which returns an array:
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 try {
InetAddress[] addresses =
InetAddress.getAllByName("www.oreilly.com"); for
(InetAddress address : addresses)
{
System.out.println(address); } }
catch (UnknownHostException ex)
{ System.out.println("Could not find www.oreilly.com"); }
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Finally, the getLocalHost() method returns
an InetAddress object for the host on which your code is
running:
 InetAddress me = InetAddress.getLocalHost();
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Find the address of the local machine
 import java.net.*;
public class MyAddress {
public static void main (String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
System.out.println(address); }
catch (UnknownHostException ex)
{ System.out.println("Could not find this computer's
address."); } } }
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Tcp/ip client 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.
The Socket class is designed to connect to server
sockets and initiate protocol exchanges.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Here are two constructors used to create client sockets:
1. Socket(String hostname,int port) : Creates a socket
connecting the local host to the named host and port,
can throw an UnknownHostException or IOException
2. Socket(InetAddress ipAddress, int port) : Creates a
socket using a preexisting InetAddress object and a port,
can throw an IOException.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 A socket can be examined at any time for the address
and port information associated with it, by use of the
following methods:
1. InetAddress getInetAddress() : Returns the InetAddress
associated with the Socket object.
2. int getPort() : Returns the remote port to which this
Socket object is connected.
3. int getLocalPort() : Returns the local port to which this
socket object is connected.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Once the socket object has been created, it can also be
examined to gain access to the input and output stream
associated with it:
 InputStream getInputStream()
 OutputStream getOutputStream()
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Advantage of Java Networking
 sharing resources
 centralize software management
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Java Networking Terminology
 The widely used java networking terminologies are given
below:
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
BY LECTURER SURAJ PANDEY CCT
COLLEGE
1) IP Address
 IP address is a unique number assigned to a node of a network e.g.
192.168.0.1 . It is composed of octets that range from 0 to 255.
 It is a logical address that can be changed.
2) Protocol
 A protocol is a set of rules basically that is followed for communication.
For example:
 TCP
 FTP
 Telnet
 SMTP
3) Port Number
 The port number is used to uniquely identify different applications. It acts
as a communication endpoint between applications.
 The port number is associated with the IP address for communication
between two applications.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
4) MAC Address
 MAC (Media Access Control) Address is a unique identifier of
NIC (Network Interface Controller). A network node can
have multiple NIC but each with unique MAC.
5) Connection-oriented and connection-less protocol
 In connection-oriented protocol, acknowledgement is sent by
the receiver. So it is reliable but slow. The example of
connection-oriented protocol is TCP.
 But, in connection-less protocol, acknowledgement is not sent
by the receiver. So it is not reliable but fast. The example of
connection-less protocol is UDP.
6) Socket
 A socket is an endpoint between two way communication.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Java Socket Programming
 Java Socket programming is used for communication
between the applications running on different JRE.
 Java Socket programming can be connection-oriented or
connection-less.
 Socket and ServerSocket classes are used for connection-
oriented socket programming and DatagramSocket and
DatagramPacket classes are used for connection-less
socket programming.
 The client in socket programming must know two
information:
1. IP Address of Server, and
2. Port number.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Socket class
 A socket is simply an endpoint for communications
between the machines. The Socket class can be used to
create a socket.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Important methods
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 ServerSocket class
 The ServerSocket class can be used to create a server
socket. This object is used to establish communication
with the clients.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Important methods
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Definition:
 UTF stands for "Unicode Transformation Unit".
TheUnicode Standard defines several character encoding
schemes for computer systems to follow. Each of these
encoding schemes are prefixed with UTF.
 Examples:
 UTF-8: only uses one byte (8 bits) to encode English
characters. It can use a sequence of bytes to encode the
other characters. UTF-8 is widely used in email systems
and on the Internet.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 UTF-16: uses two bytes (16 bits) to encode the most
commonly used characters. If needed, the additional
characters can be represented by a pair of 16-bit
numbers.
 UTF-32: uses four bytes (32 bits) to encode the
characters. It became apparent that as the Unicode
standard grew a 16-bit number is too small to represent
all the characters. UTF-32 is capable of representing
every Unicode character as one number.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 The java.io.DataInputStream.readUTF() method
reads in a string that has been encoded using a modified
UTF-8 format. The string of character is decoded from
the UTF and returned as String.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of Java Socket Programming
 Let's see a simple of java socket programming in which
client sends a text and server receives it.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
File: MyServer.java
 import java.io.*;  
 import java.net.*;  
 public class MyServer {  
 public static void main(String[] args){  
 try{  
 ServerSocket ss=new ServerSocket(6666);  
 Socket s=ss.accept();//establishes connection   
 DataInputStream dis=new DataInputStream(s.getInputStream());  
 String  str=(String)dis.readUTF();  
 System.out.println("message= "+str);  
 ss.close();  
 }catch(Exception e){System.out.println(e);}  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 File: MyClient.java
 import java.io.*;  
 import java.net.*;  
 public class MyClient {  
 public static void main(String[] args) {  
 try{      
 Socket s=new Socket("localhost",6666);  
 DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
 dout.writeUTF("Hello Server");  
 dout.flush();  
 dout.close();  
 s.close();  
 }catch(Exception e){System.out.println(e);}  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of Java Socket Programming (Read-Write both
side)
 In this example, client will write first to the server then
server will receive and print the text. Then server will
write to the client and client will receive and print the
text. The step goes on.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 File: MyServer.java
 import java.net.*;  
 import java.io.*;  
 class MyServer{  
 public static void main(String args[])throws Exception{  
 ServerSocket ss=new ServerSocket(3333);  
 Socket s=ss.accept();  
 DataInputStream din=new DataInputStream(s.getInputStream());  
 DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
 String str="",str2="";  
 while(!str.equals("stop")){  
 str=din.readUTF();  
 System.out.println("client says: "+str);  
 str2=br.readLine();  
 dout.writeUTF(str2);  
 dout.flush();  
 }  
 din.close();  
 s.close();  
 ss.close();  
 }}  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 File: MyClient.java
 import java.net.*;  
 import java.io.*;  
 class MyClient{  
 public static void main(String args[])throws Exception{  
 Socket s=new Socket("localhost",3333);  
 DataInputStream din=new DataInputStream(s.getInputStream());  
 DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
 BufferedReader br=new BufferedReader(new InputStreamReader(System.i
n  
 String str="",str2="";  
 while(!str.equals("stop")){  
 str=br.readLine();  
 dout.writeUTF(str);  
 dout.flush();  
 str2=din.readUTF();  
 System.out.println("Server says: "+str2);  
 }  
 dout.close();  
 s.close();  
 }}  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Java URL
 The Java URL class represents an URL. URL is an acronym
for Uniform Resource Locator. It points to a resource on the
World Wide Web. For example:
 http://www.cct.com/java-tutorial  
 A URL contains many information:
1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.cct.com is
the server name.
3. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port
number. If port number is not mentioned in the URL, it
returns -1.
4. File Name or directory name: In this case, index.jsp is the
file name.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Commonly used methods of Java URL class
 The java.net.URL class provides many methods. The
important methods of URL class are given below.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of Java URL class
 //URLDemo.java  
 import java.io.*;  
 import java.net.*;  
 public class URLDemo{  
 public static void main(String[] args){  
 try{  
 URL url=new URL("http://www..google.com");    
 System.out.println("Protocol: "+url.getProtocol());  
 System.out.println("Host Name: "+url.getHost());  
 System.out.println("Port Number: "+url.getPort());  
 System.out.println("File Name: "+url.getFile());   
 }catch(Exception e){System.out.println(e);}  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Output:
 Protocol: http
 Host Name: www.google.com
 Port Number: -1
 File Name:
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 The Java URLConnection class represents a
communication link between the URL and the
application. This class can be used to read and write data
to the specified resource referred by the URL.
 How to get the object of URLConnection class
 The openConnection() method of URL class returns the
object of URLConnection class. Syntax:
 public URLConnection openConnection()throws IOExc
eption{}  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Displaying source code of a webpage by
URLConnecton class
 The URLConnection class provides many methods, we
can display all the data of a webpage by using the
getInputStream() method. The getInputStream() method
returns all the data of the specified URL in the stream
that can be read and displayed.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Example of Java URLConnecton class
 import java.io.*;  
 import java.net.*;  
 public class URLConnectionExample {  
 public static void main(String[] args){  
 try{  
 URL url=new URL("http://www.Google.com");  
 URLConnection urlcon=url.openConnection();  
 InputStream stream=urlcon.getInputStream();  
 int i;  
 while((i=stream.read())!=-1){  
 System.out.print((char)i);  
 }  
 }catch(Exception e){System.out.println(e);}  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Java InetAddress class
 Java InetAddress class represents an IP address. The
java.net.InetAddress class provides methods to get the IP
of any host name for example, www.google.com,
www.facebook.com etc.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of Java InetAddress class
 Let's see a simple example of InetAddress class to get ip
address of www.Google.com website.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 import java.io.*;  
 import java.net.*;  
 public class InetDemo{  
 public static void main(String[] args){  
 try{  
 InetAddress ip=InetAddress.getByName("www.Google.com"); 
 System.out.println("Host Name: "+ip.getHostName());  
 System.out.println("IP Address: "+ip.getHostAddress());  
 }catch(Exception e){System.out.println(e);}  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
What is datagram?
 Clients and servers that communicate via a reliable
channel, such as a TCP socket, have a dedicated point-to-
point channel between themselves, or at least the illusion
of one. To communicate, they establish a connection,
transmit the data, and then close the connection. All data
sent over the channel is received in the same order in
which it was sent. This is guaranteed by the channel.
 In contrast, applications that communicate via datagrams
send and receive completely independent packets of
information. These clients and servers do not have and
do not need a dedicated point-to-point channel. The
delivery of datagrams to their destinations is not
guaranteed. Nor is the order of their arrival.BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Definition: A datagram is an independent, self-contained
message sent over the network whose arrival, arrival
time, and content are not guaranteed.
 The java.net package contains three classes to help you
write Java programs that use datagrams to send and
receive packets over the network: DatagramSocket,
DatagramPacket, and MulticastSocket An application can
send and receive DatagramPackets through a
DatagramSocket. In addition, DatagramPackets can be
broadcast to multiple recipients all listening to a
MulticastSocket.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Java DatagramSocket and DatagramPacket
 Java DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
 Java DatagramSocket class
 Java DatagramSocket class represents a connection-
less socket for sending and receiving datagram packets.
 A datagram is basically an information but there is no
guarantee of its content, arrival or arrival time.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Commonly used Constructors of DatagramSocket class
 DatagramSocket() throws SocketEeption: it
creates a datagram socket and binds it with the available
Port Number on the localhost machine.
 DatagramSocket(int port) throws
SocketEeption: it creates a datagram socket and binds
it with the given Port Number.
 DatagramSocket(int port, InetAddress address)
throws SocketEeption: it creates a datagram socket
and binds it with the specified port number and host
address.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Java DatagramPacket class
 Java DatagramPacket is a message that can be sent or
received. If you send multiple packet, it may arrive in any
order. Additionally, packet delivery is not guaranteed.
 Commonly used Constructors of DatagramPacket class
 DatagramPacket(byte[] barr, int length): it creates
a datagram packet. This constructor is used to receive
the packets.
 DatagramPacket(byte[] barr, int length,
InetAddress address, int port): it creates a datagram
packet. This constructor is used to send the packets.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Example: Java client (UDP)
BY LECTURER SURAJ PANDEY CCT
COLLEGE
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("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Create
input stream
Create
client socket
Translate
hostname to IP
address using DNS
Example: Java client (UDP), cont.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
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);
clientSocket.close();
}
}
Create datagram with
data-to-send,
length, IP addr, port
Send datagram
to server
Read datagram
from server
Example: Java server (UDP)
BY LECTURER SURAJ PANDEY CCT
COLLEGE
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);
Create
datagram socket
at port 9876
Create space for
received datagram
Receive
datagram
Example: Java server (UDP), cont
BY LECTURER SURAJ PANDEY CCT
COLLEGE
String sentence = new String(receivePacket.getData());
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);
}
}
}
Get IP addr
port #, of
sender
Write out
datagram
to socket
End of while loop,
loop back and wait for
another client connection
Create datagram
to send to client
Example of Sending DatagramPacket by
DatagramSocket
 //DSender.java  
 import java.net.*;  
 public class DSender{  
   public static void main(String[] args) throws Exception {  
     DatagramSocket ds = new DatagramSocket();  
     String str = "Welcome java";  
     InetAddress ip = InetAddress.getByName("127.0.0.1");  
      
     DatagramPacket dp = new DatagramPacket(str.getBytes(), str.len
gth(), ip, 3000);  
     ds.send(dp);  
     ds.close();  
   }  
 }  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Example of Receiving DatagramPacket by
DatagramSocket
 //DReceiver.java  
 import java.net.*;  
 public class DReceiver{  
   public static void main(String[] args) throws Exception {  
     DatagramSocket ds = new DatagramSocket(3000);  
     byte[] buf = new byte[1024];  
     DatagramPacket dp = new DatagramPacket(buf, 1024);  
     ds.receive(dp);  
     String str = new String(dp.getData(), 0, dp.getLength());  
     System.out.println(str);  
     ds.close();  
   }  
 }  
BY LECTURER SURAJ PANDEY CCT COLLEGE

Mais conteúdo relacionado

Mais procurados

What is java? Components of java
What is java?  Components of java What is java?  Components of java
What is java? Components of java lalitaaaaaa
 
Osi model
Osi modelOsi model
Osi modelOnline
 
Operating Systems - Concurrency
Operating Systems - ConcurrencyOperating Systems - Concurrency
Operating Systems - ConcurrencyEmery Berger
 
Concept of Pipelining
Concept of PipeliningConcept of Pipelining
Concept of PipeliningSHAKOOR AB
 
MULTILEVEL QUEUE SCHEDULING
MULTILEVEL QUEUE SCHEDULINGMULTILEVEL QUEUE SCHEDULING
MULTILEVEL QUEUE SCHEDULINGgarishma bhatia
 
Analysis concepts and principles
Analysis concepts and principlesAnalysis concepts and principles
Analysis concepts and principlessaurabhshertukde
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecturesubnesh
 
Presentation on java (8)
Presentation on java (8)Presentation on java (8)
Presentation on java (8)Shwetakant1
 
CORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBACORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBAPriyanka Patil
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
Operating system services 9
Operating system services 9Operating system services 9
Operating system services 9myrajendra
 

Mais procurados (20)

What is java? Components of java
What is java?  Components of java What is java?  Components of java
What is java? Components of java
 
Rapid application developmet
Rapid application developmetRapid application developmet
Rapid application developmet
 
Ftp
FtpFtp
Ftp
 
Software quality assurance
Software quality assuranceSoftware quality assurance
Software quality assurance
 
.Net
.Net.Net
.Net
 
Osi model
Osi modelOsi model
Osi model
 
Function Points
Function PointsFunction Points
Function Points
 
Network layer logical addressing
Network layer logical addressingNetwork layer logical addressing
Network layer logical addressing
 
Operating Systems - Concurrency
Operating Systems - ConcurrencyOperating Systems - Concurrency
Operating Systems - Concurrency
 
Concept of Pipelining
Concept of PipeliningConcept of Pipelining
Concept of Pipelining
 
MULTILEVEL QUEUE SCHEDULING
MULTILEVEL QUEUE SCHEDULINGMULTILEVEL QUEUE SCHEDULING
MULTILEVEL QUEUE SCHEDULING
 
Analysis concepts and principles
Analysis concepts and principlesAnalysis concepts and principles
Analysis concepts and principles
 
scheduling
schedulingscheduling
scheduling
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecture
 
Graduation Project
Graduation ProjectGraduation Project
Graduation Project
 
Presentation on java (8)
Presentation on java (8)Presentation on java (8)
Presentation on java (8)
 
المحاضرة الثالثة لغات البرمجة
المحاضرة الثالثة  لغات البرمجةالمحاضرة الثالثة  لغات البرمجة
المحاضرة الثالثة لغات البرمجة
 
CORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBACORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBA
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Operating system services 9
Operating system services 9Operating system services 9
Operating system services 9
 

Semelhante a Basic Networking in Java

Semelhante a Basic Networking in Java (20)

Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Java
JavaJava
Java
 
Socket
SocketSocket
Socket
 
Module 1 networking basics-2
Module 1   networking basics-2Module 1   networking basics-2
Module 1 networking basics-2
 
Java networking
Java networkingJava networking
Java networking
 
Java networking
Java networkingJava networking
Java networking
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
A.java
A.javaA.java
A.java
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Java
Java Java
Java
 
Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theory
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Lecture25
Lecture25Lecture25
Lecture25
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 

Mais de suraj pandey

Systemcare in computer
Systemcare in computer Systemcare in computer
Systemcare in computer suraj pandey
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructorsuraj pandey
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.netsuraj pandey
 
Basic in Computernetwork
Basic in ComputernetworkBasic in Computernetwork
Basic in Computernetworksuraj pandey
 
History of computer
History of computerHistory of computer
History of computersuraj pandey
 
Basic of Internet&email
Basic of Internet&emailBasic of Internet&email
Basic of Internet&emailsuraj pandey
 
Basic fundamental Computer input/output Accessories
Basic fundamental Computer input/output AccessoriesBasic fundamental Computer input/output Accessories
Basic fundamental Computer input/output Accessoriessuraj pandey
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.netsuraj pandey
 
Transmission mediums in computer networks
Transmission mediums in computer networksTransmission mediums in computer networks
Transmission mediums in computer networkssuraj pandey
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.netsuraj pandey
 
Introduction to computer
Introduction to computerIntroduction to computer
Introduction to computersuraj pandey
 
Computer Fundamental Network topologies
Computer Fundamental Network topologiesComputer Fundamental Network topologies
Computer Fundamental Network topologiessuraj pandey
 
Basic of Computer software
Basic of Computer softwareBasic of Computer software
Basic of Computer softwaresuraj pandey
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Javasuraj pandey
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)suraj pandey
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVAsuraj pandey
 

Mais de suraj pandey (20)

Systemcare in computer
Systemcare in computer Systemcare in computer
Systemcare in computer
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
 
Basic in Computernetwork
Basic in ComputernetworkBasic in Computernetwork
Basic in Computernetwork
 
Computer hardware
Computer hardwareComputer hardware
Computer hardware
 
Dos commands new
Dos commands new Dos commands new
Dos commands new
 
History of computer
History of computerHistory of computer
History of computer
 
Dos commands
Dos commandsDos commands
Dos commands
 
Basic of Internet&email
Basic of Internet&emailBasic of Internet&email
Basic of Internet&email
 
Basic fundamental Computer input/output Accessories
Basic fundamental Computer input/output AccessoriesBasic fundamental Computer input/output Accessories
Basic fundamental Computer input/output Accessories
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.net
 
Transmission mediums in computer networks
Transmission mediums in computer networksTransmission mediums in computer networks
Transmission mediums in computer networks
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.net
 
Introduction to computer
Introduction to computerIntroduction to computer
Introduction to computer
 
Computer Fundamental Network topologies
Computer Fundamental Network topologiesComputer Fundamental Network topologies
Computer Fundamental Network topologies
 
Basic of Computer software
Basic of Computer softwareBasic of Computer software
Basic of Computer software
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Java
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVA
 
Generics in java
Generics in javaGenerics in java
Generics in java
 

Último

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 

Último (20)

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 

Basic Networking in Java

  • 1. Networking BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 2. Java Networking  Java Networking is a concept of connecting two or more computing devices together so that we can share resources.  Java socket programming provides facility to share data between different computing devices. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 3. Socket overview  A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.  An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 4.  The java.net package in the Java platform provides a class, Socket, that implements one side of a two-way connection between your Java program and another program on the network. The Socket class sits on top of a platform-dependent implementation, hiding the details of any particular system from your Java program. By using the java.net.Socket class instead of relying on native code, your Java programs can communicate over the network in a platform- independent fashion.  Additionally, java.net includes the ServerSocket class, which implements a socket that servers can use to listen for and accept connections to clients. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 5.  The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 6.  The following steps occur when establishing a TCP connection between two computers using sockets: 1. The server instantiates a ServerSocket object, denoting which port number communication is to occur on. 2. The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port. 3. After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to. 4. The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 7. 5. On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 8. Internet addressing  Devices connected to the Internet are called nodes. Nodes that are computers are called hosts. Each node or host is identified by at least one unique number called an Internet address or an IP address. Most current IP addresses are 4-byte-long IPv4 addresses. However, a small but growing number of IP addresses are 16-byte- long IPv6 addresses. (4 and 6 refer to the version of the Internet Protocol, not the number of the bytes in the address.) Both IPv4 and IPv6 addresses are ordered sequences of bytes, like an array. They aren’t numbers, and they aren’t ordered in any predictable or useful sense. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 9.  An IPv4 address is normally written as four unsigned bytes, each ranging from 0 to 255, with the most significant byte first. Bytes are separated by periods for the convenience of human eyes. For example, the address for login.ibiblio.orgis 152.19.134.132. This is called the dotted quad format.  An IPv6 address is normally written as eight blocks of four hexadecimal digits separated by colons. For example, at the time of this writing, the address ofwww.hamiltonweather.tk is 2400:cb00:2048:0001:00 00:0000:6ca2:c665. Leading zeros do not need to be written. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 10. The InetAddress Class  The java.net.InetAddress class is Java’s high-level representation of an IP address, both IPv4 and IPv6. It is used by most of the other networking classes, including Socket, ServerSocket, URL, DatagramSocket, D atagramPacket, and more. Usually, it includes both a hostname and an IP address. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 11. Creating New InetAddress Objects  There are no public constructors in the InetAddress class. Instead,InetAddress has static factory methods that connect to a DNS server to resolve a hostname. The most common is InetAddress.getByName(). For example, this is how you look up www.oreilly.com:  InetAddress address = InetAddress.getByName("www.oreilly.com"); BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 12. import java.net.*; public class OReillyByName { public static void main (String[] args) { try { InetAddress address = InetAddress.getByName("www.oreilly.com"); System.out.println(address); } catch (UnknownHostException ex) { System.out.println("Could not find www.oreilly.com"); } } } BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 13.  % java OReillyByName www.oreilly.com/208.201.239.36 BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 14.  You can also do a reverse lookup by IP address. For example, if you want the hostname for the address 208.201.239.100, pass the dotted quad address to InetAddress.getByName():  InetAddress address = InetAddress.getByName("208.201.239.100"); System.out.println(address.getHostName());If the address you look up does not have a hostname, getHostName() simply returns the dotted quad address you supplied. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 15.   www.oreilly.com actually has two addresses. Which one getHostName() returns is indeterminate. If, for some reason, you need all the addresses of a host, call getAllByName() instead, which returns an array: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 16.  try { InetAddress[] addresses = InetAddress.getAllByName("www.oreilly.com"); for (InetAddress address : addresses) { System.out.println(address); } } catch (UnknownHostException ex) { System.out.println("Could not find www.oreilly.com"); } BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 17.  Finally, the getLocalHost() method returns an InetAddress object for the host on which your code is running:  InetAddress me = InetAddress.getLocalHost(); BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 18.  Find the address of the local machine  import java.net.*; public class MyAddress { public static void main (String[] args) { try { InetAddress address = InetAddress.getLocalHost(); System.out.println(address); } catch (UnknownHostException ex) { System.out.println("Could not find this computer's address."); } } } BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 19. Tcp/ip client 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. The Socket class is designed to connect to server sockets and initiate protocol exchanges. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 20.  Here are two constructors used to create client sockets: 1. Socket(String hostname,int port) : Creates a socket connecting the local host to the named host and port, can throw an UnknownHostException or IOException 2. Socket(InetAddress ipAddress, int port) : Creates a socket using a preexisting InetAddress object and a port, can throw an IOException. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 21.  A socket can be examined at any time for the address and port information associated with it, by use of the following methods: 1. InetAddress getInetAddress() : Returns the InetAddress associated with the Socket object. 2. int getPort() : Returns the remote port to which this Socket object is connected. 3. int getLocalPort() : Returns the local port to which this socket object is connected. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 22.  Once the socket object has been created, it can also be examined to gain access to the input and output stream associated with it:  InputStream getInputStream()  OutputStream getOutputStream() BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 23. Advantage of Java Networking  sharing resources  centralize software management BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 24. Java Networking Terminology  The widely used java networking terminologies are given below: 1. IP Address 2. Protocol 3. Port Number 4. MAC Address 5. Connection-oriented and connection-less protocol 6. Socket BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 25. 1) IP Address  IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255.  It is a logical address that can be changed. 2) Protocol  A protocol is a set of rules basically that is followed for communication. For example:  TCP  FTP  Telnet  SMTP 3) Port Number  The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications.  The port number is associated with the IP address for communication between two applications. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 26. 4) MAC Address  MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller). A network node can have multiple NIC but each with unique MAC. 5) Connection-oriented and connection-less protocol  In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of connection-oriented protocol is TCP.  But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The example of connection-less protocol is UDP. 6) Socket  A socket is an endpoint between two way communication. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 27. Java Socket Programming  Java Socket programming is used for communication between the applications running on different JRE.  Java Socket programming can be connection-oriented or connection-less.  Socket and ServerSocket classes are used for connection- oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming.  The client in socket programming must know two information: 1. IP Address of Server, and 2. Port number. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 28.  Socket class  A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 29. Important methods BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 30.  ServerSocket class  The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 31. Important methods BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 32. Definition:  UTF stands for "Unicode Transformation Unit". TheUnicode Standard defines several character encoding schemes for computer systems to follow. Each of these encoding schemes are prefixed with UTF.  Examples:  UTF-8: only uses one byte (8 bits) to encode English characters. It can use a sequence of bytes to encode the other characters. UTF-8 is widely used in email systems and on the Internet. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 33.  UTF-16: uses two bytes (16 bits) to encode the most commonly used characters. If needed, the additional characters can be represented by a pair of 16-bit numbers.  UTF-32: uses four bytes (32 bits) to encode the characters. It became apparent that as the Unicode standard grew a 16-bit number is too small to represent all the characters. UTF-32 is capable of representing every Unicode character as one number. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 34.  The java.io.DataInputStream.readUTF() method reads in a string that has been encoded using a modified UTF-8 format. The string of character is decoded from the UTF and returned as String. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 35.  Example of Java Socket Programming  Let's see a simple of java socket programming in which client sends a text and server receives it. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 36. File: MyServer.java  import java.io.*;    import java.net.*;    public class MyServer {    public static void main(String[] args){    try{    ServerSocket ss=new ServerSocket(6666);    Socket s=ss.accept();//establishes connection     DataInputStream dis=new DataInputStream(s.getInputStream());    String  str=(String)dis.readUTF();    System.out.println("message= "+str);    ss.close();    }catch(Exception e){System.out.println(e);}    }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 37.  File: MyClient.java  import java.io.*;    import java.net.*;    public class MyClient {    public static void main(String[] args) {    try{        Socket s=new Socket("localhost",6666);    DataOutputStream dout=new DataOutputStream(s.getOutputStream());    dout.writeUTF("Hello Server");    dout.flush();    dout.close();    s.close();    }catch(Exception e){System.out.println(e);}    }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 38.  Example of Java Socket Programming (Read-Write both side)  In this example, client will write first to the server then server will receive and print the text. Then server will write to the client and client will receive and print the text. The step goes on. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 39.  File: MyServer.java  import java.net.*;    import java.io.*;    class MyServer{    public static void main(String args[])throws Exception{    ServerSocket ss=new ServerSocket(3333);    Socket s=ss.accept();    DataInputStream din=new DataInputStream(s.getInputStream());    DataOutputStream dout=new DataOutputStream(s.getOutputStream());    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));    String str="",str2="";    while(!str.equals("stop")){    str=din.readUTF();    System.out.println("client says: "+str);    str2=br.readLine();    dout.writeUTF(str2);    dout.flush();    }    din.close();    s.close();    ss.close();    }}   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 40.  File: MyClient.java  import java.net.*;    import java.io.*;    class MyClient{    public static void main(String args[])throws Exception{    Socket s=new Socket("localhost",3333);    DataInputStream din=new DataInputStream(s.getInputStream());    DataOutputStream dout=new DataOutputStream(s.getOutputStream());    BufferedReader br=new BufferedReader(new InputStreamReader(System.i n    String str="",str2="";    while(!str.equals("stop")){    str=br.readLine();    dout.writeUTF(str);    dout.flush();    str2=din.readUTF();    System.out.println("Server says: "+str2);    }    dout.close();    s.close();    }}   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 41. Java URL  The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. For example:  http://www.cct.com/java-tutorial    A URL contains many information: 1. Protocol: In this case, http is the protocol. 2. Server name or IP Address: In this case, www.cct.com is the server name. 3. Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned in the URL, it returns -1. 4. File Name or directory name: In this case, index.jsp is the file name. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 42.  Commonly used methods of Java URL class  The java.net.URL class provides many methods. The important methods of URL class are given below. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 43. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 44.  Example of Java URL class  //URLDemo.java    import java.io.*;    import java.net.*;    public class URLDemo{    public static void main(String[] args){    try{    URL url=new URL("http://www..google.com");      System.out.println("Protocol: "+url.getProtocol());    System.out.println("Host Name: "+url.getHost());    System.out.println("Port Number: "+url.getPort());    System.out.println("File Name: "+url.getFile());     }catch(Exception e){System.out.println(e);}    }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 45.  Output:  Protocol: http  Host Name: www.google.com  Port Number: -1  File Name: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 46.  The Java URLConnection class represents a communication link between the URL and the application. This class can be used to read and write data to the specified resource referred by the URL.  How to get the object of URLConnection class  The openConnection() method of URL class returns the object of URLConnection class. Syntax:  public URLConnection openConnection()throws IOExc eption{}   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 47. Displaying source code of a webpage by URLConnecton class  The URLConnection class provides many methods, we can display all the data of a webpage by using the getInputStream() method. The getInputStream() method returns all the data of the specified URL in the stream that can be read and displayed. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 48. Example of Java URLConnecton class  import java.io.*;    import java.net.*;    public class URLConnectionExample {    public static void main(String[] args){    try{    URL url=new URL("http://www.Google.com");    URLConnection urlcon=url.openConnection();    InputStream stream=urlcon.getInputStream();    int i;    while((i=stream.read())!=-1){    System.out.print((char)i);    }    }catch(Exception e){System.out.println(e);}    }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 49. Java InetAddress class  Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example, www.google.com, www.facebook.com etc. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 50. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 51.  Example of Java InetAddress class  Let's see a simple example of InetAddress class to get ip address of www.Google.com website. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 52.  import java.io.*;    import java.net.*;    public class InetDemo{    public static void main(String[] args){    try{    InetAddress ip=InetAddress.getByName("www.Google.com");   System.out.println("Host Name: "+ip.getHostName());    System.out.println("IP Address: "+ip.getHostAddress());    }catch(Exception e){System.out.println(e);}    }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 53. What is datagram?  Clients and servers that communicate via a reliable channel, such as a TCP socket, have a dedicated point-to- point channel between themselves, or at least the illusion of one. To communicate, they establish a connection, transmit the data, and then close the connection. All data sent over the channel is received in the same order in which it was sent. This is guaranteed by the channel.  In contrast, applications that communicate via datagrams send and receive completely independent packets of information. These clients and servers do not have and do not need a dedicated point-to-point channel. The delivery of datagrams to their destinations is not guaranteed. Nor is the order of their arrival.BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 54.  Definition: A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.  The java.net package contains three classes to help you write Java programs that use datagrams to send and receive packets over the network: DatagramSocket, DatagramPacket, and MulticastSocket An application can send and receive DatagramPackets through a DatagramSocket. In addition, DatagramPackets can be broadcast to multiple recipients all listening to a MulticastSocket. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 55. Java DatagramSocket and DatagramPacket  Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.  Java DatagramSocket class  Java DatagramSocket class represents a connection- less socket for sending and receiving datagram packets.  A datagram is basically an information but there is no guarantee of its content, arrival or arrival time. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 56.  Commonly used Constructors of DatagramSocket class  DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port Number on the localhost machine.  DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port Number.  DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 57. Java DatagramPacket class  Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.  Commonly used Constructors of DatagramPacket class  DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets.  DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 58. Example: Java client (UDP) BY LECTURER SURAJ PANDEY CCT COLLEGE 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("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Create input stream Create client socket Translate hostname to IP address using DNS
  • 59. Example: Java client (UDP), cont. BY LECTURER SURAJ PANDEY CCT COLLEGE 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); clientSocket.close(); } } Create datagram with data-to-send, length, IP addr, port Send datagram to server Read datagram from server
  • 60. Example: Java server (UDP) BY LECTURER SURAJ PANDEY CCT COLLEGE 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); Create datagram socket at port 9876 Create space for received datagram Receive datagram
  • 61. Example: Java server (UDP), cont BY LECTURER SURAJ PANDEY CCT COLLEGE String sentence = new String(receivePacket.getData()); 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); } } } Get IP addr port #, of sender Write out datagram to socket End of while loop, loop back and wait for another client connection Create datagram to send to client
  • 62. Example of Sending DatagramPacket by DatagramSocket  //DSender.java    import java.net.*;    public class DSender{      public static void main(String[] args) throws Exception {        DatagramSocket ds = new DatagramSocket();        String str = "Welcome java";        InetAddress ip = InetAddress.getByName("127.0.0.1");               DatagramPacket dp = new DatagramPacket(str.getBytes(), str.len gth(), ip, 3000);        ds.send(dp);        ds.close();      }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 63. Example of Receiving DatagramPacket by DatagramSocket  //DReceiver.java    import java.net.*;    public class DReceiver{      public static void main(String[] args) throws Exception {        DatagramSocket ds = new DatagramSocket(3000);        byte[] buf = new byte[1024];        DatagramPacket dp = new DatagramPacket(buf, 1024);        ds.receive(dp);        String str = new String(dp.getData(), 0, dp.getLength());        System.out.println(str);        ds.close();      }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE