NETWORK
PROGRAMMING IN
JAVA
INTRODUCTION
A network represents interconnection of computers that is capable of
sharing files and information between multiple systems
The computer which recieves service is called client and the
computer which provides service is called server
The term network programming refers to writing programs that
execute across multiple devices (computers), in which the
devices are all connected to each other using a network.
The java.net package contains a set of classes and interfaces that
support communication between processes (executing applications)
that are running on the same or different hosts.
2
Network basics
Protocol:
A protocol represents a set of rules and standards that define a
certain type of network communication
There are many different protocols defining different aspects of
network communication
HTTP- Used to transfer HTML documents on the Web
FTP-Allows you to transfer binary files over the Internet
Both protocols have their own set of rules and standards on how
data is transferred
3
Network basics
IP Address:
It is a unique identification number allotted to every computer on a
network or Internet
It contains 4 integer numbers in the range of 0 to 255 and are
separated by dots
Eg: 87.248.114.14
Domain Name System:
Since it is not easy to remember IP addresses, they are often
mapped to meaningful names called domain names
Special servers called Domain Name Servers (DNS) are available
on the Internet that translate host names into IP addresses 4
Network basics
When we are typing a site address, the DNS translate this domain name
into corresponding numeric IP address and then sends the request
using the IP address.
Port:
Each computer on the Internet can provide a variety of services and the
type of service must be known before information can be transferred.
This is accomplished by using ports
Every computer with an IP address has several thousand logical ports
Each port is identified by a number from 1 to 65,535 and each port
can be allocated to a particular service.
5
Network basics
Ports 0 - 1023 are reserved for use by well-known services
Port No Protocol Description
21 FTP File Transfer Protocol
23 TELNET Remote Login
25 SMTP Simple Mail Transfer
Protocol
Data transmitted over the Internet is accompanied by addressing
information that identifies the computer(IP address) and the port for
which it is destined
The receiver checks each packet it sees for the port and sends the
data to any programs that are listening to the specified port. 6
Network basics
SOCKETS:
Sockets provide the communication mechanism between two
computers that enable you to transfer data through a particular port
Network programming usually involves a server and one or more clients. The
client sends requests for information/services own by the Server
Once the connection is established between Client and Server, they
can start sending / receiving information.
Socket acts as an interface through which sever and client can
send / receive information
It is identified by using the port number and IP address
7
Socket Communication
A server (program) runs on a specific computer and has a socket that
is bound to a specific port.
The server waits and listens to the socket for a client to make a
connection request.
Connection request
port
server
Client
8
Socket Communication
The server accepts the connection request from client.
Upon acceptance, the server gets a new socket bounds to a different
port
new socket is dedicated for serving the client that had sent request
The original socket can continue to listen for further connection
requests
port
server
port
Client
Connection
port
9
The Java Networking Package
The java.net package provides classes useful for developing
networking applications
It provides support for the two common network protocols:
TCP:
allows for reliable communication between two applications
TCP is known as a connection-oriented protocol, which means
that a connection is established and maintained between source
and destination
Guarantees that data sent from one end of the connection
actually gets to the other end and in the same order it was sent.
Otherwise, an error is reported
10
The Java Networking Package
UDP:
connection-less protocol that allows for packets of data(data
grams) to be transmitted between applications.
the destination port and IP addresses are written down in a
datagram and the datagram is sent to the destination
UDP does not guarantee that packets will be received in the
order they were sent
11
The Java Networking Package
Some of the important classes available in java.net Package are:
InetAddress
ServerSocket
Socket
DatagramPacket
DatagramSocket
URL
12
InetAddress Class
When you are establishing a connection across the Internet,
addresses are fundamental.
The InetAddress class is used to encapsulate both the numerical IP
address and the domain name for that address.
Only the name needs to be supplied to get the respective address
The InetAddress class has no visible constructors
There are 3 different methods available which return an instance of
the InetAddress Class.
13
InetAddress Class
staticInetAddress getLocalHost( ) throws UnknownHostException
returns the InetAddress object that represents the local host.
staticInetAddress getByName(String hostName) throws
UnknownHostException
returns an InetAddress for a host name passed to it.
staticInetAddress[ ] getAllByName(String hostName) throws
UnknownHostException
returns an array of InetAddresses that represent all of the addresses
that a particular name resolves to.
14
InetAddress Class: Example
import java.net.*;
class InetAddressTest
{
public static void main(String args[])
throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.yahoo.com");
System.out.println(Address);
InetAddress SW[] =
InetAddress.getAllByName("www.google.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
15
}
InetAddress Class: Example
OUTPUT
COMPAQ-PC/192.168.2.2
www.yahoo.com/106.10.170.118
www.google.com/74.125.235.50
www.google.com/74.125.235.51
www.google.com/74.125.235.52
www.google.com/74.125.235.48
www.google.com/74.125.235.49
16
InetAddress Class: Methods
String getHostAddress(): Returns a string that represents the host
address associated with the InetAddress object.
String getHostName() : Returns a string that represents the host name
associated with the InetAddress object.
17
Transmission Control Protocol
With a TCP network connection, the client computer is similar to
the person placing the telephone call, and the server computer is
similar to the person waiting for a call
A client program creates a socket on its end of the communication and
attempts to connect that socket to a server
When the connection is made, the server creates a socket object on its
end of the communication
When a TCP connection is established, the client and server have a
reliable, two-way communication stream that allows data to be
transmitted in either direction.
18
Transmission Control Protocol
Using TCP provides a Stream-based communication for data transmission
and it can detect lost transmissions and resubmit them
The two computers can communicate until the connection is closed or lost
The java.net.ServerSocket and java.net.Socket classes are the two
classes needed to create a TCP/IP connection between two computers
19
Socket-based Programs
Server ServerSocket(1234)
client
Output/write stream
Input/read stream
Socket(“128.250.25.158”, 1234)
20
Socket Class
If TCP is similar to placing a telephone call, a socket is the
telephone
The java.net.Socket class is Java's fundamental class for performing
client-side TCP operations.
The Socket class contains constructor that is used to create stream
socket that connects to specific port number associated with exactly
one host
A socket is bound to a port number so that the TCP layer can identify
the application that data destined to be sent
The actual reading and writing of data over the socket is accomplished
via the familiar stream classes.
21
Socket Class
CONSTRCUTORS
Socket(String hostName, int port)-Creates a socket that connects
to the given port number on the specified host
Socket(InetAddress ipAddress, int port)-Creates a socket that
connects to the given port number at the specified IP address
When the Socket constructor returns, it does not simply instantiate a
Socket object. Within the constructor, it actually attempts to connect to
the specified server and port.
22
Socket Class
METHODS
InetAddress getInetAddress()- tells which remote host the Socket is
connected to or, if the connection is now closed, which host the
Socket was connected to when it was connected.
int getPort() tells you which port the Socket is (or was or will be)
connected to on the remote host.
InputStream getInputStream()-returns an input stream that can read
data from the socket into a program.
You can chain this InputStream to a filter stream or reader that offers
more functionality—DataInputStream or InputStreamReader before
reading input
23
Socket Class
It's also extremely helpful to buffer the input by chaining it to a
BufferedInputStream or a BufferedReader for performance
reasons.
OutputStream getOutputStream() returns a raw OutputStream for
writing data from your application to the other end of the socket
chain this stream to a more convenient class like DataOutputStream
or OutputStreamWriter before using it.
public void close() -Closes the socket, which makes this Socket
object no longer capable of connecting again to any server.
24
Implementing a client
Java programs normally use client sockets in the following fashion:
1. The program creates a new socket with a Socket() constructor
2. The socket attempts to connect to the remote host.
3. Once the connection is established, the local and remote hosts
get input and output streams from the socket and use those
streams to send data to each other.
4. When the transmission of data is complete, one or both sides
close the connection.
25
Implementing a client: Example
Socket clientSocket = new Socket("localhost", 6789);
OutputStreamWriter outToServer = new
OutputStreamWriter(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(“Hi from client”+’\n’);
String str = inFromServer.readLine();
System.out.println(“Message from server:”+ str);
clientSocket.close();
26
ServerSocket
The java.net.ServerSocket class is used by server applications to
obtain a port and listen for client requests
A serversocket waits for requests from client to come in over the
network.
When a client Socket on a remote host attempts to connect to that
port, the server wakes up, negotiates the connection between the
client and the server, and opens a regular Socket between the two
hosts.
Once the server socket has set up the connection, the server uses a
regular Socket object to send data to the client
27
ServerSocket
CONSTRCUTORS:
public ServerSocket (int port) -creates a server socket on the port
specified by the argument.
public ServerSocket(int port, int queueLength)-creates a
ServerSocket on the specified port with the specified queue length.
queueLength specifies how many incoming clients to store in a wait
queue
public ServerSocket(int port, int qLength, InetAddress address)
the InetAddress parameter specifies the local IP address to bind to.
The InetAddress is used for servers that may have multiple IP
addresses, allowing the server to specify which of its IP addresses to
accept client requests on 28
ServerSocket
METHODS
public int getLocalPort(). Returns the port that the server socket is
listening on.
public Socket accept() - returns a Socket object representing the
connection between the remote client and the local server. It stops the
flow of execution and waits until a client connects
We use the streams returned by this Socket's getInputStream() and
getOutputStream() methods to communicate with the client
29
Implementing Server
1. A new ServerSocket is created on a particular port using a
ServerSocket() constructor.
2. The server invokes the accept() method of the ServerSocket class.
accept() blocks until a client attempts to make a connection, at which
point accept() returns a Socket object connecting the client and the
server.
3.Depending on the requirement, either getInputStream()
method, getOutputStream() method, or both are called to get input
and output streams that communicate with the client.
4.The server and the client interact according to an agreed-upon
protocol until it is time to close the connection.
30
Implementing Server:Example
5. The server, the client, or both close the connection.
6. The server returns to step 2 and waits for the next connection.
EXAMPLE:
ServerSocket server = new ServerSocket(5776);
Socket connection = server.accept( );
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
String str= inFromClient.readLine();
System.out.println(“Message from client:”+str);
DataOutputStream outToclient
= new DataOutputStream(connection.getOutputStream( ));
outToclient.writeBytes("You've connected to this server. Bye..“+’\n’);
connection.close( );
31
Client-Server Interaction via TCP
32
Client-Server Interaction via TCP:
Example
Client Machine Code
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String args[]) throws Exception {
String sentence;
String sent1;
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
33
Client-Server Interaction via TCP:
Example
Client Machine Code
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence+'\n');
System.out.println("Message from Server:");
sent1= inFromServer.readLine();
System.out.println(sent1);
clientSocket.close();
}
}
34
Client-Server Interaction via TCP:
Example
Server Machine Code:
import java.io.*;
import java.net.*;
public class SimpleServer {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
35
Client-Server Interaction via TCP:
Example
Server Machine Code:
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
System.out.println("Message from Client:");
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
outToClient.writeBytes("Thanks for
greetings"+'\n');
}
}
}
36
Client-Server Interaction via TCP:
Example
37
Client-Server Interaction via TCP:
Example
38
Client-Server Interaction via TCP:
Example
39
User Datagram Protocol
User Datagram Protocol (UDP) provides a protocol for sending
packets of data called datagrams between applications.
UDP can be compared to mailing someone a letter(datagram), where a
client sends a datagram to a server without actually connecting to the
server
UDP does not guarantee that packets will be received in the order they
were sent or that they will even be delivered at all
The java.net.DatagramPacket and java.net.DatagramSocket classes
are used to send and receive datagram packets using UDP
This is suitable for applications in which speed is the significant factor
40
User Datagram Protocol
Datagram packets are used to implement a connectionless
packet delivery service supported by the UDP protocol
Each packet needs to have destination address and each packet
might be routed differently, and might arrive in any order.
The format of datagram packet is:
Msg | length | Host | serverPort
The sender of a message uses a datagram socket to send a packet,
and a recipient uses a datagram socket to receive a message.
When a message is sent, the recipient does not need to be available.
Similarly, when a message is received, the sender does not need to be
still available.
41
DatagramPacket
The DatagramPacket class represents a datagram packet,
and it is used by both the sender and receiver of a packet.
CONSTRCUTORS:
There are two types of constructors for DatagramPacket:
The first constructor is used to receive data from the net; the second is
for data that you will send to the net.
public DatagramPacket(byte[] buffer, int length)-Creates a datagram
packet for receiving a packet of the specified size. The buffer will
contain the incoming packet
The array of bytes passed in to these constructors is used to contain
the data of the incoming packet, and typically are empty arrays.
42
DatagramPacket
public DatagramPacket(byte[] buffer, int length, InetAddress
address, int port)-Creates a datagram packet for sending a
packet of the specified size. The buffer contains the data of the
packet, and the address and port denote the recipient.
METHODS:
The DatagramPacket class contains get and set methods for the various
attributes of the datagram packet
byte[] getData();
void setData(byte[] buf);
void setPort(int port);
int getPort();
InetAddress getAddress();
void setAddress(InetAddress a);
43
DatagramSocket
The java.net.DatagramSocket class is used by both the sender and the
recipient of a datagram packet to send and receive a packet,
respectively
CONSTRUCTORS
public DatagramSocket(int port)-Creates a datagram socket on the
localhost computer at the specified port.
public DatagramSocket(int port, InetAddress address)-Creates a
datagram socket using the specified port and host address
44
DatagramSocket
METHODS
public void send(DatagramPacket packet)-Sends the specified
datagram packet. The DatagramPacket object contains the destination
information of the packet
public void receive(DatagramPacket packet)-This method receives a
single UDP datagram from the network and stores it in the pre-existing
DatagramPacket object
Like the accept( ) method in the ServerSocket class, this method
blocks the calling thread until a datagram arrives
45
DatagramSocket
METHODS
public void send(DatagramPacket packet)-Sends the specified
datagram packet. The DatagramPacket object contains the destination
information of the packet
public void receive(DatagramPacket packet)-This method receives a
single UDP datagram from the network and stores it in the pre-existing
DatagramPacket object
Like the accept( ) method in the ServerSocket class, this method
blocks the calling thread until a datagram arrives
46
Receiving a Datagram Packet
To receive a datagram packet, the following steps are performed:
1. Create an array of bytes large enough to hold the data of the incoming
packet.
2. A DatagramPacket object is instantiated using the array of bytes.
3. A DatagramSocket is instantiated, and it is specified which port (and
specific localhost address, if necessary) on the localhost the socket
will bind to.
4. The receive() method of the DatagramSocket class is invoked, passing
in the DatagramPacket object. This blocks the execution of further
code until a datagram packet is received or a time out occurs.
47
Sending a Datagram Packet
To receive a datagram packet, the following steps are performed:
1. Create an array of bytes large enough to hold the data of the packet to
be sent, and fill the array with the data.
2. Create a new DatagramPacket object that contains the array of bytes,
as well as the server name and port number of the recipient.
3. A DatagramSocket is instantiated, and it is specified which port (and
specific localhost address, if necessary) on the localhost the socket
will bind to.
4. The send() method of the DatagramSocket class is invoked, passing in
the DatagramPacket object.
48
Receiving a Datagram Packet
import java.net.*;
import java.io.*;
public class PacketReceiver
{ public static void main(String [] args) throws Exception
{
byte [] buffer = new byte[1024];
DatagramPacket packet =
new DatagramPacket(buffer, buffer.length);
DatagramSocket socket = new DatagramSocket(5002);
System.out.println(“Waiting for a packet...”);
socket.receive(packet);
System.out.println(“Just received packet from “+
packet.getSocketAddress());
buffer = packet.getData();
System.out.println(new String(buffer));
}
} 49
Sending a Datagram Packet
import java.net.*;
import java.io.*;
public class PacketSender
{
public static void main(String [] args)
{
try
{
String data =
“You have just received a packet of data sent using UDP”;
byte [] buffer = data.getBytes();
DatagramPacket packet = new DatagramPacket(buffer,buffer.length,
InetAddress.getLocalHost(), 5002);
50
Sending a Datagram Packet
DatagramSocket socket = new DatagramSocket(5003);
System.out.println(“Sending a packet...”);
socket.send(packet);
}catch(IOException e)
{
e.printStackTrace();
}
}
}.
51
OUTPUT
52
OUTPUT
53
mport 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);
54
clientSocket.send(sendPacket);
Client
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);
55
clientSocket.send(sendPacket);
Client
DatagramPacket receivePacket =new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
56
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());
57
InetAddress IPAddress = receivePacket.getAddress();
Server
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =new DatagramPacket(sendData,
sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
58
OUTPUT
59
Client/server socket interaction: UDP
60
URL -Uniform Resource Locator
URL is a reference (an address) to a resource on the Internet
A URL can be broken down into parts, as follows:
protocol://host:port/path?query#ref
Eg:http://www.javapassion.com:80/javaintro/index.html#Networking_A
Part Meaning Required
scheme or protocol Internet protocol to be followed. e.g. http, https, ftp, Yes
mailto, etc. This defines the syntax of the URL.
domain or hostname This is the destination location for the URL. It can be Yes
a hostname or ip address.
port The port to be used to connect to the location. No
path or pathname This is typically a file or location on the web server. No
query_string or This is the data to be passed to software running on No
search the server.
fragment_id or ref This specifies a part or a position within the overall No
61
resource or document
URL -Uniform Resource Locator
The java.net.URL class represents a URL. The URL class has
several constructors for creating URLs
CONSTRUCTOR
public URL(String protocol, String host, int port, String file)
Creates a URL by putting together the given parts
public URL(String url)- Creates a URL from the given String.
The URL class contains many methods for accessing the various parts of
the URL being represented:
public String getPath().
public String getQuery()
public String getProtocol()
public String getHost()
public String getFile()
public String getRef() 62
URL class:Example
import java.net.*;
import java.io.*;
public class URLDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL(args[0]);
System.out.println("URL is:" + url.toString());
System.out.println("protocol is:"+ url.getProtocol());
System.out.println("file name is:" + url.getFile());
System.out.println("host is:" + url.getHost());
System.out.println("path is:" + url.getPath());
63
URL class:Example
import java.net.*;
import java.io.*;
public class URLDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL(args[0]);
System.out.println("URL is:" + url.toString());
System.out.println("protocol is:"+ url.getProtocol());
System.out.println("file name is:" + url.getFile());
System.out.println("host is:" + url.getHost());
System.out.println("path is:" + url.getPath());
64
URL class:Example
System.out.println("port is:" + url.getPort());
System.out.println("query is:" + url.getQuery());
System.out.println("ref is:" + url.getRef());
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
65
URL class:Example
OUTPUT
Java http://www.example.com:80/example.php?y=2#results
URL is:http://www.example.com:80/example.php?y=2#results
protocol is:http
file name is:/example.php?y=2
host is:www.example.com
path is:/example.php
port is:80
query is:y=2
ref is:results
66