CN Final
CN Final
CN Final
Socket Programming
Java Socket programming is used for communication between the applications running on
different JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
Sockets provide the communication mechanism between two computers using TCP. 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. The client and the server can now communicate by writing to and reading
from the socket.
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.
The following steps occur when establishing a TCP connection between two computers
using sockets −
● The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
● The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.
● After the server is waiting, a client instantiates a Socket object, specifying the server
name and the port number to connect to.
● The constructor of the Socket class attempts to connect the client to the specified
server and the port number. If communication is established, the client now has a
Socket object capable of communicating with the server.
● 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.
After the connections are established, communication can occur using I/O streams. Each
socket has both an OutputStream and an InputStream. The client's OutputStream is
connected to the server's InputStream, and the client's InputStream is connected to the
server's OutputStream.
TCP is a two-way communication protocol, hence data can be sent across both streams at the
same time. Following are the useful classes providing complete set of methods to implement
sockets.
The java.net.ServerSocket class is used by server applications to obtain a port and listen for
client requests.
The java.net.Socket class represents the socket that both the client and the server use to
communicate with each other. The client obtains a Socket object by instantiating one,
whereas the server obtains a Socket object from the return value of the accept() method.
PROGRAM 2
To implement echo server and client in java using TCP sockets.
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();
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);
}
}
}
// CLIENT SIDE CODE
import java.io.*;
import java.net.*;
public class MyClient
{
public static void main(String[] args)
{
try
{
Socket s = new Socket("localhost",6666);
DataOutputStream dout =
newDataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
SERVER CLIENT
PROGRAM 3
To implement date server and client in java using TCP sockets
// SERVER SIDE CODE
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s = new ServerSocket(9999);
while(true)
{
System.out.println("Waiting For Connection...");
Socket soc = s.accept();
DataOutputStream out = new
DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date" + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
import java.io.*;
import java.net.*;
class DateClient
{
public static void main(String args[]) throws Exception
{
Socket soc = new Socket("localhost", 9999);
BufferedReader in = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
System.out.println(in.readLine());
}
}
OUTPUT:
SERVER CLIENT
PROGRAM 4
To implement chat server and client in java using TCP sockets
// SERVER SIDE CODE
import java.net.*;
import java.io.*;
public class MyServer1
{
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();
}
}
// CLIENT SIDE CODE
import java.net.*;
import java.io.*;
public class MyClient1
{
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.in));
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();
}
}
OUTPUT:
SERVER CLIENT
PROGRAM 5
import java.io.*;
import java.net.*;
import java.util.*;
while(true)
{
String input= dis.readUTF();
if(input.equals("bye"))
break;
if(operation.equals("+"))
{
result=oprnd1+oprnd2;
}
else if(operation.equals("-"))
{
result=oprnd1-oprnd2;
}
else if(operation.equals("*"))
{
result=oprnd1*oprnd2;
}
else
{
result=oprnd1/oprnd2;
}
}
s.close();
ss.close();
}
}
import java.io.*;
import java.net.*;
import java.util.*;
while(true)
{
System.out.println("Enter the equation in the form: ");
System.out.println(" 'operand operator operand' ");
Scanner sc=new Scanner(System.in);
String inp= sc.nextLine();
if(inp.equals("bye"))
break;
dos.writeUTF(inp);
int ans= dis.readInt();
System.out.println("Answer=" +ans);
}
s.close();
}
}
OUTPUT:
SERVER CLIENT
PROGRAM 6
To implement sorting of data using a remote client
// SERVER SIDE CODE
import java.io.*;
import java.net.*;
import java.util.*;
class Server
{
public static void main(String args[]) throws Exception
{
ServerSocket ss = new ServerSocket(7777);
Socket s = ss.accept();
System.out.println("connected...");
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
int r, i = 0;
int n = din.readInt();
int a[] = new int[n];
System.out.println("data");
int count = 0;
System.out.println("Receiving Data...");
for(i=0;i<n;i++)
{
a[i] = din.readInt();
}
System.out.println("Data Received");
System.out.println("Sorting Data...");
Arrays.sort(a);
for(i=0; i<n; i++)
{
dout.writeInt(a[i]);
}
System.out.println("\nData Sent Successfully");
s.close();
ss.close();
}
}
// CLIENT SIDE CODE
import java.io.*;
import java.net.*;
import java.util.Scanner;
SERVER CLIENT
PROGRAM 7
To implement bubble sort and sort data using a remote client
// SERVER SIDE CODE
import java.io.*;
import java.net.*;
class ServerBubble
{
public static void main(String args[]) throws Exception
{
ServerSocket ss = new ServerSocket(7777);
Socket s = ss.accept();
System.out.println("connected.....");
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
int r,i=0;
int n=din.readInt();
int a[] = new int[n];
System.out.println("data:");
int count = 0;
System.out.println("Receiving data...");
for(i=0;i<n;i++)
{
a[i]=din.readInt();
}
System.out.println("Data Received");
System.out.println("Sorting Data...");
int temp=0;
for(int k=0; k<n;k++)
{
for(int j=1;j<(n-k);j++)
{
if(a[j-1] > a[j])
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
System.out.println("Data Sorted");
System.out.println("Sending Data....");
for(i=0; i<n;i++)
{
dout.writeInt(a[i]);
}
System.out.println("\nData Sent Successfully");
s.close();
ss.close();
}
}
import java.io.*;
import java.net.*;
import java.util.Scanner;
class ClientBubble
{
public static void main(String args[]) throws Exception
{
Socket s = new Socket("localhost", 7777);
if(s.isConnected())
{
System.out.println("Connected to server");
}
System.out.println("Enter size of array:");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int a[] = new int[n];
System.out.println("Enter element to array:");
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeInt(n);
for(int i=0; i<n;i++)
{
a[i] = scanner.nextInt();
dout.writeInt(a[i]);
}
System.out.println("Data Sent");
DataInputStream din = new DataInputStream(s.getInputStream());
int r;
System.out.println("Receiving Sorted Data...");
for(int i=0;i<n;i++)
{
a[i] = din.readInt();
System.out.print(" "+a[i]+" ");
}
s.close();
}
}
OUTPUT:
SERVER CLIENT
PROGRAM 8
Write a code simulating ARP protocol
// SERVER SIDE CODE
import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(3333);
Socket clsct=obj.accept();
while(true)
{
DataInputStream din=new
DataInputStream(clsct.getInputStream());
DataOutputStream dout=new
DataOutputStream(clsct.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80", "165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0; i<ip.length; i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
// CLIENT SIDE CODE
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{
try
{
Socket clsct=new Socket("localhost", 3333);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new
DataOutputStream(clsct.getOutputStream());
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Logical address(IP):");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Physical Address is: "+str);
clsct.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
SERVER CLIENT
PROGRAM 9
To implement echo server and client in java using UDP sockets
// SERVER SIDE CODE
import java.io.*;
import java.net.*;
if (data(receive).toString().equals("bye"))
{
System.out.println("Client sent bye...EXITING");
break;
}
import java.io.*;
import java.net.*;
import java.util.*;
InetAddress ip = InetAddress.getLocalHost();
byte buf[] = null;
while(true)
{
String inp = sc.nextLine();
buf = inp.getBytes();
DatagramPacket DpSend = new DatagramPacket(buf, buf.length, ip,
1234);
ds.send(DpSend);
if(inp.equals("bye"))
break;
}
}
}
OUTPUT:
SERVER CLIENT
PROGRAM 10
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp
{
public static void main(String args[])
{
try
{
DatagramSocket server = new DatagramSocket(1309);
while(true)
{
byte[] sendbyte = new byte[1024];
byte[] receivebyte = new byte[1024];
DatagramPacket receiver = new DatagramPacket(receivebyte,
receivebyte.length);
server.receive(receiver);
String str = new String(receiver.getData());
String s = str.trim();
InetAddress addr = receiver.getAddress();
int port = receiver.getPort();
String ip[] = {"165.165.80.80", "165.165.79.1"};
String mac[] = {"6A:08:AA:C2", "8A:BC:E3:FA"};
for(int i=0;i<mac.length;i++)
{
if(s.equals(mac[i]))
{
sendbyte = ip[i].getBytes();
DatagramPacket sender = new
DatagramPacket(sendbyte, sendbyte.length, addr, port);
server.send(sender);
break;
}
}
break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
/ / CLIENT SIDE CODE
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp
{
public static void main(String args[])
{
try
{
DatagramSocket client = new DatagramSocket();
InetAddress addr = InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new byte[1024];
byte[] receivebyte = new byte[1024];
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Physical address (MAC):");
String str = in.readLine();
sendbyte = str.getBytes();
DatagramPacket sender = new DatagramPacket(sendbyte,
sendbyte.length, addr, 1309);
client.send(sender);
DatagramPacket receiver = new DatagramPacket(receivebyte,
receivebyte.length);
client.receive(receiver);
String s = new String(receiver.getData());
System.out.println("The Logical Address is(IP): " + s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
SERVER CLIENT
PROGRAM 11
Study of TCP/UDP performance
TCP
TCP stands for Transmission Control Protocol. It is a transport layer protocol that facilitates
the transmission of packets from source to destination. It is a connection-oriented protocol
that means it establishes the connection prior to the communication that occurs between the
computing devices in a network. This protocol is used with an IP protocol, so together, they
are referred to as a TCP/IP.
The main functionality of the TCP is to take the data from the application layer. Then it
divides the data into a several packets, provides numbering to these packets, and finally
transmits these packets to the destination. The TCP, on the other side, will reassemble the
packets and transmits them to the application layer. As we know that TCP is a
connection-oriented protocol, so the connection will remain established until the
communication is not completed between the sender and the receiver.
Features of TCP protocol:
TCP is a transport layer protocol as it is used in transmitting the data from the sender to
the receiver.
2. Reliable
TCP is a reliable protocol as it follows the flow and error control mechanism. It also
supports the acknowledgment mechanism, which checks the state and sound arrival of the
data. In the acknowledgment mechanism, the receiver sends either positive or negative
acknowledgment to the sender so that the sender can get to know whether the data packet
has been received or needs to resend.
3. Order of the data is maintained
This protocol ensures that the data reaches the intended receiver in the same order in
which it is sent. It orders and numbers each segment so that the TCP layer on the
destination side can reassemble them based on their ordering.
4. Connection-oriented
It is a connection-oriented service that means the data exchange occurs only after the
connection establishment. When the data transfer is completed, then the connection will
get terminated.
5. Full duplex
It is a full-duplex means that the data can transfer in both directions at the same time.
6. Stream-oriented
TCP is a stream-oriented protocol as it allows the sender to send the data in the form of a
stream of bytes and also allows the receiver to accept the data in the form of a stream of
bytes. TCP creates an environment in which both the sender and receiver are connected
by an imaginary tube known as a virtual circuit. This virtual circuit carries the stream of
bytes across the internet.
UDP
The UDP stands for User Datagram Protocol. Its working is similar to the TCP as it is also
used for sending and receiving the message. The main difference is that UDP is a
connectionless protocol. Here, connectionless means that no connection establishes prior to
communication. It also does not guarantee the delivery of data packets. It does not even care
whether the data has been received on the receiver's end or not, so it is also known as the
"fire-and-forget" protocol. It is also known as the "fire-and-forget" protocol as it sends the
data and does not care whether the data is received or not. UDP is faster than TCP as it does
not provide the assurance for the delivery of the packets.
TCP UDP
Full form It stands for Transmission Control Protocol. It stands for User Datagram
Protocol.
Speed TCP is slower than UDP as it performs error UDP is faster than TCP as it does
checking, flow control, and provides assurance not guarantee the delivery of data
for the delivery of packets.
Header size The size of TCP is 20 bytes. The size of the UDP is 8 bytes.
Acknowledgment TCP uses the three-way-handshake concept. In UDP does not wait for any
this concept, if the sender receives the ACK, acknowledgment; it just sends the
then the sender will send the data. TCP also has data.
the ability to resend the lost data.
Flow control It follows the flow control mechanism in which This protocol follows no such
mechanism too many packets cannot be sent to the receiver mechanism.
at the same time.
Error checking TCP performs error checking by using a It does not perform any error
checksum. When the data is corrected, then the checking, and also does not resend
data is retransmitted to the receiver. the lost data packets.
Applications This protocol is mainly used where a secure and This protocol is used where fast
reliable communication process is required, like communication is required and
military services, web browsing, and e-mail. does not care about the reliability
like VoIP, game streaming, video
and music streaming, etc.
PROGRAM 12
Study of different types of routing
Routing
o A Router is a process of selecting path along which the data can be transferred from
source to the destination. Routing is performed by a special device known as a router.
o A Router works at the network layer in the OSI model and internet layer in TCP/IP
model
o A router is a networking device that forwards the packet based on the information
available in the packet header and forwarding table.
o The routing algorithms are used for routing the packets. The routing algorithm is
nothing but a software responsible for deciding the optimal path through which packet
can be transmitted.
o The routing protocols use the metric to determine the best path for the packet delivery.
The metric is the standard of measurement such as hop count, bandwidth, delay,
current load on the path, etc. used by the routing algorithm to determine the optimal
path to the destination.
o The routing algorithm initializes and maintains the routing table for the process of
path determination.
Types of Routing
Routing can be classified into three categories:
o Static Routing
o Default Routing
o Dynamic Routing
Static Routing
o Static Routing is also known as Nonadaptive Routing.
o It is a technique in which the administrator manually adds the routes in a routing
table.
o A Router can send the packets for the destination along the route defined by the
administrator.
o In this technique, routing decisions are not made based on the condition or topology
of the networks
Default Routing
o Default Routing is a technique in which a router is configured to send all the packets
to the same hop device, and it doesn't matter whether it belongs to a particular
network or not. A Packet is transmitted to the device for which it is configured in
default routing.
o Default Routing is used when networks deal with the single exit point.
o It is also useful when the bulk of transmission networks have to transmit the data to
the same hp device.
o When a specific route is mentioned in the routing table, the router will choose the
specific route rather than the default route. The default route is chosen only when a
specific route is not mentioned in the routing table.
Dynamic Routing
o It is also known as Adaptive Routing.
o It is a technique in which a router adds a new route in the routing table for each packet
in response to the changes in the condition or topology of the network.
o Dynamic protocols are used to discover the new routes to reach the destination.
o In Dynamic Routing, RIP and OSPF are the protocols used to discover the new routes.
o If any route goes down, then the automatic adjustment will be made to reach the
destination.
o All the routers must have the same dynamic routing protocol in order to exchange the
routes.
o If the router discovers any change in the condition or topology, then router broadcast
this information to all other routers.
Routing algorithm
o In order to transfer the packets from source to the destination, the network layer must
determine the best route through which packets can be transmitted.
o Whether the network layer provides datagram service or virtual circuit service, the
main job of the network layer is to provide the best route. The routing protocol
provides this job.
o The routing protocol is a routing algorithm that provides the best path from the source
to the destination. The best path is the path that has the "least-cost path" from source
to the destination.
o Routing is the process of forwarding the packets from source to the destination but the
best route to send the packets is determined by the routing algorithm.
2. Route Calculation
Each node uses Dijkstra's algorithm on the graph to calculate the optimal routes to all
nodes.
o The Link state routing algorithm is also known as Dijkstra's algorithm which is used
to find the shortest path from one node to every other node in the network.
o The Dijkstra's algorithm is an iterative, and it has the property that after kth iteration of
the algorithm, the least cost paths are well known for k destination nodes.