19it082 CN Record
19it082 CN Record
19it082 CN Record
LAB RECORD
Semester IV/Even
Submitted By,
1
TABLE OF CONTENTS
Page No.
Exp. No TITLE
1 Basic programs 3
Develop a concurrent server that spawns several threads, one for each
3 client requesting a specific service 14
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.
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
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.
6
7
CODE:
UDP_SERVER.java
import java.net.*;
import java.util.*;
8
UDP CLIENT PROGRAM
UDP_CLIENT.java
import java.net.*;
import java.util.*;
}
}
9
OUTPUT:
10
CODE :
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
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.
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
PROCEDURE:
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++;
}
}
}
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;
}
21
ClientSide.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
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();
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:
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;
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;
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();
}
OUTPUT:
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){}
}
}
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;
}
3. Create the stub and skeleton objects using the rmic tool.
rmic AdderRemote
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
40