Network Programming in Java
Network Programming in Java
Network Programming in Java
PROGRAMMING IN
JAVA
INTRODUCTION
A network represents interconnection of computers that is capable of
sharing files and information between multiple systems
2
Network basics
Protocol:
A protocol represents a set of rules and standards that define a
certain type of network communication
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
Eg: 87.248.114.14
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
5
Network basics
Ports 0 - 1023 are reserved for use by well-known services
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
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.
new socket is dedicated for serving the client that had sent request
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
10
The Java Networking Package
UDP:
connection-less protocol that allows for packets of data(data
grams) to be transmitted between applications.
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.
13
InetAddress Class
staticInetAddress getLocalHost( ) throws UnknownHostException
returns the InetAddress object that represents the local host.
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.
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
When the connection is made, the server creates a socket object on its
end of the communication
18
Transmission Control Protocol
The two computers can communicate until the connection is closed or lost
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
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
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.
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.
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:
25
Implementing a client: Example
Socket clientSocket = new Socket("localhost", 6789);
26
ServerSocket
The java.net.ServerSocket class is used by server applications to
obtain a port and listen for client requests
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 int getLocalPort(). Returns the port that the server socket is
listening on.
29
Implementing Server
1. A new ServerSocket is created on a particular port using a
ServerSocket() constructor.
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.*;
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 does not guarantee that packets will be received in the order they
were sent or that they will even be delivered at all
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.
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.
44
DatagramSocket
METHODS
public void send(DatagramPacket packet)-Sends the specified
datagram packet. The DatagramPacket object contains the destination
information of the packet
45
DatagramSocket
METHODS
public void send(DatagramPacket packet)-Sends the specified
datagram packet. The DatagramPacket object contains the destination
information of the packet
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.
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.
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
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