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