19it082 CN Record

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Thiagarajar College of Engineering, Madurai – 625015

Department of Information Technology

LAB RECORD

Lab Course Code 18IT470

Lab Course Name Computer Networks Lab

Programme B.Tech. (IT)

Semester IV/Even

Academic Year 2020 – 21

Submitted By,

Student Name : Sanjaykumar S

Register Number : 19IT082

1
TABLE OF CONTENTS

Page No.
Exp. No TITLE

1 Basic programs 3

Develop a simple single client-server chatting application using


(i)Connection-oriented and
2 5
(ii) Connectionless sockets (Use StreamMode Socket API
and Datagram Socket API respectively

Develop a concurrent server that spawns several threads, one for each
3 client requesting a specific service 14

Extend the single client – single server chatting application developed


using connection-oriented sockets to a multiple client –single server
4 19
chatting application
using threads

Develop a multicast chatting tool that will be used to communicate


5 among a multicast group 24

Implement a simple file transfer protocol (FTP) using connection-


6 oriented and connectionless sockets 28

Implement sliding window and stop and wait techniques to establish


7 flow control between a sender 32

8 Develop a remote service request-response application using RMI 37

2
EXP. NO: 1 BASIC PROGRAMS

AIM:
1) To manipulate the IP address of the system.
2) To obtain the information about the host, port and protocol.

1. PROGRAM TO MANIPULATE THE IP ADDRESS OF A SYSTEM.

CODE:
import java.net.*;
class IP
{
public static void main(String args[])
{
try
{
InetAddress ia = InetAddress.getLocalHost();
System.out.println("The IP address of local host is "+ia);
ia=InetAddress.getByName(args[0]);
System.out.println("The IP address of "+args[0]+"is"+ia);
}
catch(UnknownHostException ue)
{
System.out.println("Error Occured"+ue);
}
}
}

OUTPUT:

3
2. PROGRAM TO OBTAIN THE INFORMATION ABOUT THE
(A)HOST (B)PORT (C)PROTOCOL

CODE:
import java.io.*;
import java.net.*;
class INFO
{
public static void main(String args []) throws MalformedURLException
{
URL url = new URL("https://www.tce.edu/");
try
{
System.out.println("Host name is " + url.getHost());
System.out.println("Port no. is " + url.getPort());
System.out.println("Protocol used is " + url.getProtocol());
}
catch (Exception e)
{
System.out.println("Error Occurred"+e);
}
}
}

OUTPUT:

RESULT:
Thus, programs to Manipulate IP address of a system and to obtain the information about the
host, port and protocol was written in java and executed.

4
EX.NO: 2

DEVELOP A SIMPLE SINGLE CLIENT-SERVER CHATTING APPLICATION


USING CONNECTION-ORIENTED AND CONNECTIONLESS SOCKETS

AIM:
To develop a simple single client-server chatting application using Connection-oriented
and connectionless sockets in ‘Java’

PROCEDURE:

BACKGROUND:
Interprocess communication (IPC) is the backbone of distributed computing. Processes are
runtime representations of a program. IPC refers to the ability for separate, independent processes
to communicate among themselves to collaborate on a task. The following figure illustrates basic
IPC:

Two or more processes engage in a protocol – a set of rules to be observed by the participants
for data communication. A process can be a sender at some instant of the communication and can
be a receiver of the data at another instant of the communication. When data is sent from one process
to another single process, the communication is said to be unicast. When data is sent from one
process to more than one process at the same time, the communication is said to be multicast.

SOCKETS:

The Socket API is a low-level programming facility for implementing IPC. The upper-layer
facilities are built on top of the operations provided by the Socket API. The Socket API was
originally provided as part of the Berkeley UNIX OS, but has been later ported to all operating
systems including Sun Solaris and Windows systems. The Socket API provides a programming
construct called a “socket”. A process wishing to communicate with another process must create an
instance or instantiate a socket. Two processes wishing to communicate can instantiate sockets and
then issue operations provided by the API to send and receive data. Note that in network parlance,
a packet is the unit of data transmitted over the network. Each packet contains the data (payload)
and some control information (header) that includes the destination address.A socket is uniquely
identified by the IP address of the machine and the port number at which the socket is opened (i.e.
bound to). Port numbers are allocated 16 bits in the packet headers and thus can be at most 66535.

5
Well-known processes like FTP, HTTP and etc., have their sockets opened on dedicated port
numbers (less than or equal to 1024). Hence,sockets corresponding to user-defined processes have
to be run on port numbers greater than 1024.

Types of Sockets
The User Datagram Protocol (UDP) transports packets in a connectionless manner. In a
connectionless communication, each data packet (also called datagram) is addressed and routed
individually and may arrive at the receiver in any order. For example, if process 1 on host A sends
datagrams m1 and m2 successively to process 2 on host B, the datagrams may be transported on the
network through different routes and may arrive at the destination in any of the two orders: m1, m2
or m2, m1.

The Transmission Control Protocol (TCP) is connection-oriented and transports a stream of


data over a logical connection established between the sender and the receiver . As a result, data sent
from a sender to a receiver is guaranteed to be received in the order they were sent. In the above
example, messages m1 and m2 are delivered to process 2 on host B in the same order they were
sent from process 1 on host A. A socket programming construct can use either UDP or TCP
transport protocols. Sockets that use UDP for transport of packets are called “datagram” sockets
and sockets that use TCP for
transport are called “stream” sockets.

The Connectionless Datagram Socket


In Java, two classes are provided for the datagram socket API:
(a) The DatagramSocket class for the sockets
(b) The DatagramPacket class for the packets exchanged.A process wishing to send or receive
data using the datagram socket API must instantiate a DatagramSocket object, which is bound
to a UDP port of the machine and local to the process. To send a datagram to another process,
the sender process must instantiate a DatagramPacket object that carries the following
information:
(1) a reference to a byte array that contains the payload data and
(2) the destination address (the host ID and port number to which the receiver
process’ DatagramSocket object is bound).
At the receiving process, a DatagramSocket object must be instantiated and bound to a local
port – this port should correspond to the port number carried in the datagram packet of the sender.
To receive datagrams sent to the socket, the receiving process must instantiate a DatagramPacket
object that references a byte array and call the receive method of the DatagramSocket object,
specifying as argument, a reference to the DatagramPacket object.

The program flow in the sender and receiver process is illustrated


in Figure 3 and the key methods used for communication using connectionless sockets are
summarized in Table 1.

6
7
CODE:

UDP SENDER PROGRAM:

UDP_SERVER.java

import java.net.*;
import java.util.*;

public class UDP_SERVER


{
public static void main(String[] args) throws Exception
{
int port1=6000,port2=6001;
Scanner inp=new Scanner(System.in);
InetAddress ip = InetAddress.getLocalHost();
DatagramSocket ds1 = new DatagramSocket(port1);
DatagramSocket ds2 = new DatagramSocket();
while(true)
{
byte arr1[] = new byte[1000];
DatagramPacket dp1 = new DatagramPacket(arr1, arr1.length);
ds1.receive(dp1);
String s1=new String(arr1);
if(s1.trim().equals("End"))
break;
System.out.println("Client : "+s1.trim());
System.out.print("Your reply: ");
String s2 = inp.nextLine();
byte arr2[]=s2.getBytes();
DatagramPacket dp2 = new DatagramPacket(arr2, arr2.length, ip, port2);
if(s2.trim().equals("End"))
{
ds2.send(dp2);
break;
}
ds2.send(dp2);
}
}
}

8
UDP CLIENT PROGRAM

UDP_CLIENT.java

import java.net.*;
import java.util.*;

public class UDP_CLIENT


{
public static void main(String[] args) throws Exception
{
int port1=6000,port2=6001;
Scanner inp=new Scanner(System.in);
InetAddress ip = InetAddress.getLocalHost();
DatagramSocket ds1 = new DatagramSocket();
DatagramSocket ds2 = new DatagramSocket(port2);
while(true)
{
System.out.print("Your message : ");
String s1 = inp.nextLine();
byte arr1[]=s1.getBytes();
DatagramPacket dp1 = new DatagramPacket(arr1, arr1.length, ip, port1);
if(s1.trim().equals("End"))
{
ds1.send(dp1); break;
}
ds1.send(dp1);
byte arr2[] = new byte[1000];
DatagramPacket dp2 = new DatagramPacket(arr2, arr2.length);
ds2.receive(dp2);
String s2=new String(arr2);
if(s2.trim().equals("End"))
break;
System.out.println("Server : "+s2.trim());
}

}
}

9
OUTPUT:

The Connection-Oriented (Stream-Mode) Socket

10
CODE :

TCP SERVER PROGRAM: Server.java

import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{
static void send(String str,Socket s) throws Exception
{
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
dos.writeUTF("Server: "+str);
dos.flush();
}
static void recieve(Socket s) throws Exception
{
DataInputStream dis=new DataInputStream(s.getInputStream()); String str=(String)dis.readUT
F();
System.out.println(str);
}
public static void main(String[] args)
{
ServerSocket ss;
Scanner input;
try
{
ss=new ServerSocket(6666); Socket s=ss.accept();
input=new Scanner(System.in);
while(true)
{
System.out.print("Enter your message: ");
send(input.nextLine(),s);
recieve(s);
}
}
catch(Exception e)
{
System.out.println(e);
}
}

11
TCP CLIENT PROGRAM: Client.java

import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
static void send(String str,Socket s) throws Exception
{
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
dos.writeUTF("Client: "+str);
dos.flush();
}
static void recieve(Socket s) throws Exception
{
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println(str);
}
public static void main(String[] args)
{
Socket s;
Scanner input;
try
{
s=new Socket("localhost",6666); input=new Scanner(System.in);
while(true)
{
recieve(s);
System.out.print("Your Message :"); send(input.nextLine(),s);
send(input.nextLine(),s);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

12
OUTPUT:

RESULT:

Thus, the programs for a simple single client-server chatting application using Connection-
oriented and Connectionless sockets are implemented in Java and the results are verified.

13
EXP NO: 3

DEVELOP A CONCURRENT SERVER THAT SPAWNS SEVERAL THREADS, ONE FOR


EACH CLIENT REQUESTING A SPECIFIC SERVICE

AIM:
To develop a concurrent server that spawns several threads, one for each client requesting a
specific service

PROCEDURE:
CONCURRENT SERVER:
The server can be iterative, i.e. it iterates through each client and serves one request at a time.
Alternatively, a server can handle multiple clients at the same time in parallel, and this type of a
server is called a concurrent server.

DIFFERENCES BETWEEN CONCURRENT SERVER AND ITERATIVE SERVER:


Iterative Server Concurrent Server
An iterative server processes only one A Concurrent Server processes multiple requests at a
request at a time. time.

Iterative servers cause too much blocking


for most applications
Avoiding blocking results in better performance.
Easy to build More difficult to design and build
Unnecessary delay Better performance

APIS AND METHODS REQUIRED TO IMPLEMENT CONCURRENT SERVERS:


• Java.net contains the inbuilt packages for networking
• Get the host address or IP address as the argument
• Close the socket using the close() function.
• Create a thread for the socket
• Buffered reader to get the input of the user from the client
• Put the thread to sleep using thread.sleep()
• Send the output to the client using PrintStream

14
CODE:

DUIServer.java
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
class duiThread extends Thread
{
Socket clientSocket;
duiThread(Socket cs)
{
clientSocket = cs;
}
String str="";
String str2="";
public void run( )
{
try
{
BufferedReader br = new
BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
str = br.readLine( );

String med[]={"Abidec","Acemetacin","Aclacin","Albendazole","Amoxycillin","Antazoline"
,"Aspirin","AZT","Bacitracin","Baclofen","Benadryl","Benzydamine","brufen","Calamine","Calcif e
rol"," Calpol","Cannabis","Capreomycin","Caprin","Carbenoxolone","Cardura","Chloral hydrate","
Chloroquine","Cinoxacin","Codis","Corwin","Cyklokapron","Dantolene","Dimyril","Dobutamine","
Domi","Rentac","Pantope","Digene","Betadine","Zoale- F","BurnHeal","Meftal- Forte","Anthraxin"
,"Sinharest","Cold free","Avil","Ascoril","Otrivin","Gluformin","Charmicide","Gaviscon","Triminic
","Tast y mol","Dollow","Fepanil"};

String symptom[]={"Multi-vitamin","Non-
steroidal anti inflammatory drug","Anti- cancer drug","To treat intestinal worms","Antibiotic drug (p
encillin)","Treat allergic conjunctivitis","Analgesic drug","Azidothymidine","Anti-
bacterial drug","Muscle-
relaxant drug","Cough remedy","Treat Perkinson’s disease","Pain killer","Soothe skinirritation","Vit
amin D","Paracetamol","Central nervous system depressant","Antibacterial drug to treat TB","Aspiri
n","Ulcer-
healing","Anti- hypertensive drug","Sleeping drug","Treat malaria","Antibiotic drug","Anagesic dru
g","Mild heart failure","Blood clotting","Muscle relaxant","Cough remedy","Heart failure","Nausea,
vomiting","Gastro- intestinal problems","Gastro-
intestinal problems","Gastrointestinal problems","Antiseptic medicine","Skin irritability","Anti infla
mmatory skin ointment","Migraine, Painkiller","Antibiotic","Cold and throat infection","Cold","Alle

15
rgy","Cough syrup","Nasaldrops","Diabetic medicine","Gastrointestinal problems","Gastro-
intestinal problems","Cold, running nose","Paracetamol650","Paracetamol 650","Paracetamol"};

int i;
int flag=0;
for(i=0;i<med.length;i++)
{
if(med[i].equals(str))
{
str2=symptom[i];
flag=1;
break;
}
}
if(flag==0)
{
str2="Invalid input!!!";
}

Thread.sleep(200);
PrintStream ps = new PrintStream(clientSocket.getOutputStream( ));
ps.println(str2); ps.flush( );
clientSocket.close( );
}
catch(Exception e)
{
e.printStackTrace( );
}
}
}
class DUIServer
{
public static void main(String[ ] args)
{
try
{
int serverPort = 3000;
ServerSocket calcServer = new ServerSocket(serverPort);
while (true)
{
Socket clientSocket = calcServer.accept( );
duiThread thread = new duiThread(clientSocket);
thread.start( );
}
}
catch(Exception e)

16
{
e.printStackTrace( );
}
}
}

DUIClient.java
import java.io.*;
import java.net.*;
import java.util.*;
class DUIClient
{
public static void main(String[] args)
{
Scanner ip = new Scanner(System.in);
try
{
InetAddress serverHost = InetAddress.getLocalHost();
int serverPort = 3000;
long startTime = System.currentTimeMillis( );
System.out.println("Enter medicine: ");
String str=ip.nextLine( );
Socket clientSocket = new Socket(serverHost, serverPort);
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
ps.println(str);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStre
am()));
String str2="";
str2 = br.readLine();
System.out.println(" The medicine is used to treat "+str2);
long endTime = System.currentTimeMillis();
System.out.println(" \n Time consumed for receiving the feedback from the server:"+(endTim
e-startTime)+" milliseconds");
clientSocket.close( );
}
catch(Exception e)
{
e.printStackTrace( );
}
}
}

17
SCREENSHOTS:
Server side:

Client 1:

Client 2:

Client 3

RESULT:
Thus, the programs for concurrent server that spawns several threads, one for each client
requesting a specific service is executed in java and the results are verified.

18
EX NO: 4

IMPLEMENTATION OF MULTIPLE CLIENT –SINGLE SERVER CHATTING


APPLICATION USING THREADS
AIM:
To implement multiple client –single server chatting application using threads.

PROCEDURE:

Procedure for ServerSide class:


• The server runs an infinite loop to keep accepting incoming requests.
• When a request comes, it assigns a new thread to handle the communication part.
• The sever also stores the client name into a vector, to keep a track of connected devices.
• The vector stores the thread object corresponding to the current request.
• The helper class uses this vector to find the name of recipient to which message is to be
delivered.
• As this vector holds all the streams, handler class can use it to successfully deliver
messages to specific clients.
• Invoke the start() method.

Procedure for ClientHandler class:


• Whenever the handler receives any string, it breaks it into the message and recipient
part.
• It uses Stringtokenizer for this purpose with ‘#’ as the delimiter.
• Here it is assumed that the string is always of the format:
• message # recipient
• It then searches for the name of recipient in the connected clients list, stored as a vector
in the server.
• If it finds the recipients name in the clients list, it forwards the message on its output
stream with the name of the sender prefixed to the message.

19
CODE:
ServerSide.java
import java.io.*;
import java.util.*;
import java.net.*;
public class ServerSide
{
static Vector<ClientHandler> ar = new Vector<>();
static int i = 0;
public static void main(String[] args) throws IOException
{
ServerSocket ss = new ServerSocket(1234);
Socket s;

while (true)
{
s = ss.accept();
System.out.println("New client request received : " + s);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Creating a new handler for this client...");
ClientHandler mtch = new ClientHandler(s,"client " + i, dis, dos);
Thread t = new Thread(mtch);
System.out.println("Adding this client to active client list");
ar.add(mtch);

t.start();
i++;
}
}
}

class ClientHandler implements Runnable


{
Scanner scn = new Scanner(System.in);
private String name;
final DataInputStream dis;
final DataOutputStream dos; Socket s;
boolean isloggedin;
public ClientHandler(Socket s, String name, DataInputStream dis, DataOutputStream dos)
{
this.dis = dis; this.dos = dos; this.name = name; this.s = s;
this.isloggedin=true;
}

20
@Override
public void run()
{
String received;
while (true)
{
try
{
received = dis.readUTF();
System.out.println(received);
if(received.equals("logout"))
{
this.isloggedin=false; this.s.close();
break;
}

StringTokenizer st = new StringTokenizer(received, "#"); String MsgToSend = st.nextTok


en();
String recipient = st.nextToken();

for (ClientHandler mc : ServerSide.ar)


{
if (mc.name.equals(recipient) && mc.isloggedin==true)
{
mc.dos.writeUTF(this.name+" : "+MsgToSend);
break;
}
}
}
catch (IOException e) {}
}
try
{
this.dis.close();
this.dos.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

21
ClientSide.java

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ClientSide


{
final static int ServerPort = 1234;

public static void main(String args[]) throws UnknownHostException, IOException


{
Scanner scn = new Scanner(System.in);
InetAddress ip = InetAddress.getByName("localhost");
Socket s = new Socket(ip, ServerPort);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
Thread sendMessage = new Thread(new Runnable()
{
@Override
public void run()
{
while (true)
{
String msg = scn.nextLine();
try
{
dos.writeUTF(msg);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});

Thread readMessage = new Thread(new Runnable()


{
@Override
public void run() {

while (true) {
try
{
String msg = dis.readUTF();

22
System.out.println(msg);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});

sendMessage.start();
readMessage.start();

}
}

OUTPUT:

RESULT:
Thus, the multiple client – single server chatting application using threads is implemented in
Java and the results are verified.

23
EX NO: 5
DEVELOP A MULTICAST CHATTING TOOL THAT WILL BE USED TO
COMMUNICATE AMONG A MULTICAST GROUP

AIM:
To develop a multicast chatting tool that will be used to communicate among a multicast
group.

PROCEDURE:
• Import the necessary packages such as java.net, util, io and so on.
• Begin a public class and initiate the necessary variables.
• Generate a condition for improper arguments handling
• Get the multicast address using InnetAddress.getByName()
• Get the port number and the name of the client.
• Create a constructor for the MultiSocket function and pass the port number as the
argument.
• Use the join Group method to admit the clients into the Group.
• Create a new thread for each of the clients to handle the incoming messages.
• Start the thread using thread.start()
• Begin loop until the termination message is passed
• Get messages from the client, Store it in the buffer
• Create datagrams for the messages
• Send the datagram.
• Create the run method for the thread to run
• The message should be got in the buffer and send along with the identifier as the name of
the client.

24
CODE:
GroupChat.java
import java.net.*;
import java.io.*;
import java.util.*;
public class GroupChat
{
private static final String TERMINATE = "Exit";
static String name;
static volatile boolean finished = false;
public static void main(String[] args)
{
if (args.length != 2)
System.out.println("Two arguments required: <multicast-host> <port -number>");
else
{
try
{
InetAddress group = InetAddress.getByName(args[0]);
int port = Integer.parseInt(args[1]);
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
name = sc.nextLine();
MulticastSocket socket = new MulticastSocket(port);

socket.setTimeToLive(0);

socket.joinGroup(group);
Thread t = new Thread(new
ReadThread(socket,group,port));

t.start();

System.out.println("Start typing messages...\n");


while(true)
{
String message;
message = sc.nextLine();
if(message.equalsIgnoreCase(GroupChat.TERMINATE))
{
finished = true;
socket.leaveGroup(group);
socket.close();
break;
}

25
message = name + ": " + message;
byte[] buffer = message.getBytes();
DatagramPacket datagram = new
DatagramPacket(buffer,buffer.length,group,port);
socket.send(datagram);
}
}
catch(SocketException se)
{
System.out.println("Error creating socket");
se.printStackTrace();
}
catch(IOException ie)
{
System.out.println("Error reading/writing from/to socket");
ie.printStackTrace();
}
}
}
}
class ReadThread implements Runnable
{
private MulticastSocket socket;
private InetAddress group;
private int port;
private static final int MAX_LEN = 1000;
ReadThread(MulticastSocket socket,InetAddress group,int port)
{
this.socket = socket;
this.group = group;
this.port = port;
}
@Override
public void run()
{
while(!GroupChat.finished)
{
byte[] buffer = new byte[ReadThread.MAX_LEN];
DatagramPacket datagram = new
DatagramPacket(buffer,buffer.length,group,port);
String message;
try
{
socket.receive(datagram);
message = new
String(buffer,0,datagram.getLength(),"UTF-8");

26
if(!message.startsWith(GroupChat.name))
System.out.println(message);
}
catch(IOException e)
{
System.out.println("Socket closed!");
}
}
}
}

OUTPUT:

Client 1 Client 2 Client 3

RESULT
Thus, the programs for developing a multicast chatting tool that will be used to communicate
among a multicast group is developed.

27
EX NO: 6
IMPLEMENT A SIMPLE FILE TRANSFER PROTOCOL (FTP)
USINGCONNECTION- ORIENTED AND CONNECTIONLESS SOCKETS
AIM:
To implement a simple file transfer protocol (FTP) using connection-oriented and
connectionless sockets.

PROCEDURE:
FileServer
• Create a package called Server.
• Import all the necessary packages including jaa.net and java.io.
• Create a public class and create instance for socket and assign the port.
• Create the socket.accept() function for the client to accept the request.
• Create the method to saveFile called savefile with client socket as the parameter.
• Create instances for Data Input stream and File Output Stream respectively.
• Implement counter mechanism to calculate the amount of bytes sent and decrement counter
to identify the remaining bytes and print it.
• Close the file stream and socket.

FileClient
• Create a package Client.
• Import all the necessary files and create a private Socket instance.
• Create a constructor FileClient with host port and filename as parameters.
• Connect to the socket using Socket() constructor
• Create sendfile method and create instances for DataInputStream and FileOutputStream.
• Implement buffer to verify the receival of data and retransmit if not received.
• Print the message if received.
• Close the file stream and socket.
• End.

28
CODE:
FileServer.java
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class FileServer extends Thread


{
private ServerSocket ss;
public FileServer(int port)
{
try
{
ss = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
while (true)
{
try
{
Socket clientSock = ss.accept();
saveFile(clientSock);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void saveFile(Socket clientSock) throws IOException
{
DataInputStream dis = new DataInputStream(clientSock.getInputStream());
FileOutputStream fos = new FileOutputStream("E:/CN/out.txt");
byte[] buffer = new byte[4096];
int filesize = 15123;
int read = 0;
int totalRead = 0;

29
int remaining = filesize;
while((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0)
{
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
fos.close();
dis.close();
}
public static void main(String[] args)
{
FileServer fs = new FileServer(1988);
fs.start();
}
}

FileClient.java
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class FileClient


{
private Socket s;

public FileClient(String host, int port, String file)


{
try
{
s = new Socket(host, port);
sendFile(file);
}
catch (Exception e)
{
e.printStackTrace();
}
}

public void sendFile(String file) throws IOException


{
DataOutputStream dos = new DataOutputStream(s.getOutputStream());

30
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
while (fis.read(buffer) > 0)
{
dos.write(buffer);
}
System.out.println("File sent...");
fis.close();
dos.close();
}

public static void main(String[] args)


{
FileClient fc = new FileClient("localhost", 1988, "D:/19IT082 CN LAB/in.txt");
}
}

OUTPUT:

‘in.txt’ is Copied to E:/CN, file name as ‘out.txt’

RESULT
Thus an application for the File transfer from the server to the client has been implemented and
verified.

31
EX.NO: 7
IMPLEMENT SLIDING WINDOW AND STOP AND WAIT TECHNIQUES TO
ESTABLISH FLOW CONTROL BETWEEN A SENDER AND RECEIVER
AIM:
To implement Stop and Wait ARQ Protocol and Sliding Window Protocol using TCP in Java.

DESCRIPTION:
Stop and Wait ARQ Protocol
Stop-and-wait ARQ, also referred to as alternating bit protocol, is a method in
telecommunications to send information between two connected devices. It ensures that information
is not lost due to dropped packets and that packets are received in the correct order.
Sliding Window Protocol
Sliding window protocol is a flow control protocol. It allows the sender to send multiple
frames before needing the acknowledgements. Sender slides its window on receiving the
acknowledgements for the sent frames. This allows the sender to send more frames.

PROCEDURE:
Algorithm: Server.java
1. sequence be 0
2. Accept new packet and assign sequence to it.
3. Send packet sequence with sequence number sequence.
4. Set timer for recently sent packets.
5. If error free acknowledgment from receiver and NextFrameExpected → sequence then
sequence → NextFrameExpected.
6. If time out then go to step3.
7. Stop.
Client.java
1. Start.
2. NextFrameExpected → 0, repeat steps 3 always.
3. If error-free frame received and sequence= NextFrameExpected, then pass packet to higher
layer and NextFrameExpected → NextFrameExpected+1(modulo 2).
4. Stop.

32
CODE:
Sender.java

import java.io.*;
import java.net.*;
public class Sender
{
Socket sender;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,str, msg;
int n,i=0,sequence=0;
Sender(){}
public void run()
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Waiting for Connection ............. ");
sender = new Socket("localhost",2005);
sequence=0;
out=new ObjectOutputStream(sender.getOutputStream());
out.flush();
in=new ObjectInputStream(sender.getInputStream());
str=(String)in.readObject();
System.out.println("receiver > "+str);
System.out.println("Enter the data to send ");
packet=br.readLine(); n=packet.length();
do
{
try
{
if(i<n)
{
msg=String.valueOf(sequence);
msg=msg.concat(packet.substring(i,i+1));
}
else if(i==n)
{
msg="end";
out.writeObject(msg);
break;
}
out.writeObject(msg);
sequence=(sequence==0)?1:0;
out.flush();

33
System.out.println("Data Sent>"+msg);
ack=(String)in.readObject();
System.out.println("Waiting for ack .. ");
if(ack.equals(String.valueOf(sequence)))
{
i++;
System.out.println("receiver > "+" packet received");
}
else
{
System.out.println("Time out resending data ");
sequence=(sequence==0)?1:0;
}
}
catch(Exception e){}
}
while(i<n+1);
System.out.println("All data sent. Exiting.");
}
catch(Exception e){}
finally
{
try
{
in.close();
out.close();
sender.close();
}
catch(Exception e){}
}
}
public static void main(String args[])
{
Sender s=new Sender(); s.run();
}
}

34
Receiver.java
import java.io.*;
import java.net.*;
public class Receiver{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Receiver(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
reciever = new ServerSocket(2005,10);
System.out.println("waiting for connection...");
connection=reciever.accept();
sequence=0;
System.out.println("Connection established :");
out=new ObjectOutputStream(connection.getOutputStream());
out.flush();
in=new ObjectInputStream(connection.getInputStream());
out.writeObject("connected .");

do{
try{
packet=(String)in.readObject();
if(Integer.valueOf(packet.substring(0,1))==sequence){
data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("receiver >"+packet);
}
else
{
System.out.println("receiver >"+packet +" duplicate data");
}if(i<3){
out.writeObject(String.valueOf(sequence));i++;
}else{
out.writeObject(String.valueOf((sequence+1)%2));
i=0;
}
} catch(Exception e){}
}while(!packet.equals("end"));
System.out.println("Data recived="+data);
out.writeObject("connection ended .");
}catch(Exception e){}

35
finally{
try{in.close();
out.close();
reciever.close();
}
catch(Exception e){}
}
}

public static void main(String args[]){


Receiver s=new Receiver();
while(true){
s.run();
}
}
}

OUTPUT:

RESULT:
Stop and Wait ARQ Protocol and Sliding Window Protocol is implemented using TCP in
Java.

36
EX.NO: 8
DEVELOP A REMOTE SERVICE REQUEST-RESPONSE APPLICATION USING RMI

AIM:
To implement a remote service request-response application using Remote Method
Invocation (RMI) in Java.

PROCEDURE:
MyClient.java
• Import the package for remote method invocation and the util. package.
• Provide the lookup option in Naming to the method.
• Declare the variables.
• Get Voter ID from the user.
• Pass the voter ID entered by the user to the checkvote method to verify the voter ID using
stub.
• Handle the returned values appropriately to the applicable conditions.
• When verified get the choice of selection to vote from the user
• Pass it to another method using instance of Vote in the method called vote().
• Appropriately handle the returned values.
• Get authorized password for verification and pass it to checkresult() method.
• Appropriately handle the returned values.
• Handle exceptions caused using try catch block.
• End.
MyServer.java
• Import the package used for remote method invocation.
• Import the package for RMI registry.
• Create an object to be passed to the remote method.
• Rebind using the rebind property by providing the hostname.
• Handle exceptions for this.
• End

37
CODE:
1. Create the remote interface

import java.rmi.*;
public interface Adder extends Remote
{
public int add(int x, int y) throws RemoteException;
}

2. Provide the implementation of the remote interface


import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder
{
AdderRemote()throws RemoteException
{
super();
}
public int add(int x,int y)
{
return x+y;
}
}

3. Create the stub and skeleton objects using the rmic tool.
rmic AdderRemote

4. Start registry service by the rmiregistry tool.


start rmiregistry 5000

5. Create and run the server application


import java.rmi.*;
import java.rmi.registry.*;
public class MyServer
{
public static void main(String args[])
{
try
{
Adder stub=new AdderRemote(); Naming.rebind("rmi://localhost:5000/sonoo",stub);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

38
6. Create and run the client application

import java.rmi.*;
public class MyClient
{
public static void main(String args[])
{
try
{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(64,4));
}
catch(Exception e){}
}
}

OUTPUT:

39
RESULT

Thus, we have successfully implemented a remote service request-response application using


Remote Method Invocation (RMI) in Java.

40

You might also like