SlideShare a Scribd company logo
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
PRACTICAL NO:1 
Aim: Write a program for implementing Client Server communication model. 
Practical 1 A 
A client server based program using TCP to find if the number entered is prime. 
Code: client.java 
importjava.net.*; 
importjava.io.*; 
class Client 
{ 
public static void main(String args[]) 
{ 
try{ 
Socket cs = new Socket("LocalHost",8001); 
BufferedReaderbr = new BufferedReader(new 
InputStreamReader(System.in)); 
System.out.println("Enter a number : "); 
int a = Integer.parseInt(br.readLine()); 
DataOutputStream out = new DataOutputStream(cs.getOutputStream()); 
out.writeInt(a); 
DataInputStream in = new DataInputStream(cs.getInputStream()); 
System.out.println(in.readUTF()); 
cs.close(); 
} 
catch (Exception e) { 
System.out.println(e.toString()); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Code: server.java 
importjava.net.*; 
importjava.io.*; 
class Server 
{ 
public static void main(String args[]) { 
try{ 
ServerSocketss = new ServerSocket(8001); 
System.out.println("Server Running Succesfully... "); 
Socket s = ss.accept(); 
System.out.println("Client Request Accepted.."); 
DataInputStream in = new DataInputStream(s.getInputStream()); 
int x= in.readInt(); 
DataOutputStreamotc = new DataOutputStream(s.getOutputStream()); 
for(int i=2; i<=x; i++) { 
if(x%i==0) { 
if(i==x) 
otc.writeUTF(x + " is a Prime"); 
else 
otc.writeUTF(x + " is not a Prime"); 
break; 
} 
} 
} 
catch (Exception e) { 
System.out.println(e.toString()); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
} 
OUTPUT: Client 
Fig 1.1: Client Output 
OUTPUT: Server 
Fig 1.2: Server Output
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Practical 1 B: A client server TCP based chatting application 
Code:ChatClient.java 
importjava.net.*; 
importjava.io.*; 
classChatClient 
{ 
public static void main(String args[]) 
{ 
try{ 
Socket s = new Socket("Localhost",8000); 
BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in)); 
DataOutputStream out = new DataOutputStream(s.getOutputStream()); 
DataInputStream in = new DataInputStream(s.getInputStream()); 
String msg; 
System.out.println("To stop chatting with server type STOP"); 
System.out.print("Client Says: "); 
while((msg = br.readLine()) != null) 
{ 
out.writeBytes(msg+"n"); 
if(msg.equals("STOP")) 
break; 
System.out.println("Server Says : "+in.readLine()); 
System.out.print("Client Says : "); 
} 
br.close(); 
in.close(); 
out.close(); 
s.close();
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
} 
catch(Exception e) 
{ 
e.printStackTrace(); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Code:ChatServer.java 
importjava.net.*; 
importjava.io.*; 
classChatServer 
{ 
public static void main(String args[]) { 
try{ 
ServerSocketss = new ServerSocket(8000); 
System.out.println("Waiting for client to connect.."); 
Socket s = ss.accept(); 
System.out.println("Client Connected"); 
BufferedReaderbr = new BufferedReader(new 
InputStreamReader(System.in)); 
DataOutputStream out = new DataOutputStream(s.getOutputStream()); 
DataInputStream in = new DataInputStream(s.getInputStream()); 
String receive, send; 
while((receive = in.readLine()) != null) 
{ 
if(receive.equals("STOP")) 
break; 
System.out.println("Client Says : "+receive); 
System.out.print("Server Says : "); 
send = br.readLine(); 
out.writeBytes(send+"n"); 
} 
br.close(); 
in.close(); 
out.close();
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
s.close(); 
} 
catch(Exception e) 
{ 
e.printStackTrace(); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
OUTPUT: Client 
Fig 1.3: Client Window 
OUTPUT: Server 
Fig 1.4: Server Window
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Practical 1C: A client server based program using UDP to find if the number 
entered is evenor odd. 
Sonali. Parab. 
Code: udpClientEO.java 
importjava.io.*; 
importjava.net.*; 
public class udpClientEO 
{ 
public static void main(String args[]) 
{ 
try{ 
DatagramSocket ds = new DatagramSocket(1000); 
BufferedReaderbr = new BufferedReader(new 
InputStreamReader(System.in)); 
System.out.println("Enter a number : "); 
String num = br.readLine(); 
byte b[] = new byte[1024]; b=num.getBytes(); 
DatagramPacketdp = new 
DatagramPacket(b,b.length,InetAddress.getLocalHost(),2000); ds.send(dp); 
byteb1[] = new byte[1024]; 
DatagramPacketdp1 = new DatagramPacket(b1,b1.length); 
ds.receive(dp1); 
String str = new String(dp1.getData(),0,dp1.getLength()); 
System.out.println(str); 
} 
catch(Exception e) 
{ 
e.printStackTrace(); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Code: udpServerEO.java 
importjava.io.*; 
importjava.net.*; 
public class udpServerEO 
{ 
public static void main(String args[]) 
{ 
try{ 
DatagramSocket ds = new DatagramSocket(2000); 
byte b[] = new byte[1024]; 
DatagramPacketdp = new DatagramPacket(b,b.length); 
ds.receive(dp); 
String str = new String(dp.getData(),0,dp.getLength()); 
System.out.println(str); 
int a= Integer.parseInt(str); 
String s= new String(); 
if (a%2 == 0) 
s = "Number is even"; 
else 
s = "Number is odd"; 
byteb1[] = new byte[1024]; b1 = s.getBytes(); 
DatagramPacketdp1 = new 
DatagramPacket(b1,b1.length,InetAddress.getLocalHost(),1000); 
ds.send(dp1); 
} 
catch(Exception e) 
{ 
e.printStackTrace(); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output : Client 
Fig 1.5: Client Window 
Output : Server 
Fig 1.6: Server Window
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Practical 1D: A client server based program using UDP to find the factorial of the entered 
number. 
Sonali. Parab. 
Code: udpClientFact.java 
import java.io.*; 
import java.net.*; 
public class udpClientFact 
{ 
public static void main(String args[]) { 
try{ 
DatagramSocket ds = new DatagramSocket(1000); 
BufferedReader br = new BufferedReader(new 
InputStreamReader(System.in)); 
System.out.println("Enter a number : "); 
String num = br.readLine(); 
byte b[] = new byte[1024];b=num.getBytes(); 
DatagramPacket dp = new 
DatagramPacket(b,b.length,InetAddress.getLocalHost(),2000); 
ds.send(dp); byte b1[] = new byte[1024]; 
DatagramPacket dp1 = new DatagramPacket(b1,b1.length); 
ds.receive(dp1); 
String str = new String(dp1.getData(),0,dp1.getLength()); 
System.out.println(str); 
} 
catch(Exception e) { 
e.printStackTrace(); 
} 
}}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Code: udpServerFact.java 
import java.io.*; 
import java.net.*; 
public class udpServerFact 
{ 
public static void main(String args[]){ 
try { 
DatagramSocket ds = new DatagramSocket(2000); 
byte b[] = new byte[1024]; 
DatagramPacket dp = new DatagramPacket(b,b.length); 
ds.receive(dp); 
String str = new String(dp.getData(),0,dp.getLength()); 
System.out.println(str); 
int a= Integer.parseInt(str); int f = 1, i; 
String s= new String(); 
for(i=1;i<=a;i++) 
f=f*i; 
s=Integer.toString(f); 
String str1 = "The Factorial of " + str + " is : " + f; byte b1[] = new 
byte[1024]; b1 = str1.getBytes(); 
DatagramPacket dp1 = new 
DatagramPacket(b1,b1.length,InetAddress.getLocalHost(),1000); 
ds.send(dp1); 
} 
catch(Exception e) { 
e.printStackTrace(); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: Client 
Fig 1.7: Client Output 
Output: Server 
Fig 1.8: Server Output
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Practical 1E: A multicast Socket example. 
Code: BroadcastClient.java 
import java.net.*; 
import java.io.*; 
public class BroadcastClient 
{ 
public static final int PORT = 1234; 
public static void main(String args[])throws Exception 
{ 
MulticastSocket socket; 
DatagramPacket packet; 
InetAddress address; 
address = InetAddress.getByName("239.1.2.3"); socket = new 
MulticastSocket(PORT); 
//join a Multicast group and wait for a message socket.joinGroup(address); 
byte[] data = new byte[100]; 
packet = new DatagramPacket(data,data.length); 
for(;;) 
{ 
// receive the packets 
socket.receive(packet); 
String str = new String(packet.getData()); 
System.out.println("Message received from "+ packet.getAddress() + " 
Message is : "+str); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Code: BroadcastServer.java 
import java.net.*; 
import java.io.*; 
import java.util.*; 
public class BroadcastServer 
{ 
public static final int PORT = 1234; 
public static void main(String args[])throws Exception 
{ 
MulticastSocket socket; 
DatagramPacket packet; 
InetAddress address; 
address = InetAddress.getByName("239.1.2.3"); 
socket = new MulticastSocket(); 
// join a Multicast group and send the group messages 
socket.joinGroup(address); 
byte[] data = null; 
for(;;) 
{ 
Thread.sleep(10000); 
System.out.println("Sending "); 
String str = ("This is Neha Calling "); 
data = str.getBytes(); 
packet = new DatagramPacket(data, str.length(),address,PORT); 
//Sends the packet 
socket.send(packet); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: Client 
Fig 1.9: Client Output 
Output: Server 
Fig 1.10: Server Output
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
PRACTICAL NO: 2 
Aim: Write a program to show the object communication using RMI. 
Practical 2A: A RMI based application program to display current date and time. 
Code: 
1. InterDate.java 
importjava.rmi.*; 
public interface InterDate extends Remote 
{ 
public String display() throws Exception; 
} 
2. ServerDate.java 
importjava.rmi.*; 
importjava.rmi.server.*; 
importjava.util.*; 
public class ServerDate extends UnicastRemoteObject implements InterDate 
{ 
publicServerDate() throws Exception 
{ 
} 
public String display() throws Exception 
{ 
String str = ""; 
Date d = new Date(); 
str = d.toString(); 
returnstr; 
} 
public static void main(String args[]) throws Exception 
{ 
ServerDates1 = new ServerDate(); 
Naming.bind("DS",s1); 
System.out.println("Object registered....."); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
3. ClientDate.java 
importjava.rmi.*; 
importjava.io.*; 
public class ClientDate 
{ 
public static void main(String args[]) throws Exception 
{ 
String s1; 
InterDateh1 = (InterDate)Naming.lookup("DS"); 
s1 = h1.display(); 
System.out.println(s1); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: 
Fig 2.1: Client Window 
Fig 2.2:Server Window
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Fig 2.3: Client Window
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Practical 2B: A RMI based application program that converts digits to words, e.g. 123 will 
be converted to one two three. 
Sonali. Parab. 
Code: 
1. InterConvert.java 
importjava.rmi.*; 
public interface InterConvert extends Remote 
{ 
public String convertDigit(String no) throws Exception; 
} 
2. ServerConvert.java 
importjava.rmi.*; 
importjava.rmi.server.*; 
public class ServerConvert extends UnicastRemoteObject implements InterConvert 
{ 
publicServerConvert() throws Exception 
{ 
} 
public String convertDigit(String no) throws Exception 
{ 
String str = ""; 
for(int i = 0; i <no.length(); i++) 
{ 
int p = no.charAt(i); 
if( p == 48) 
{ 
str += "zero "; 
} 
if( p == 49) 
{ 
str += "one "; 
} 
if( p == 50) 
{ 
str += "two "; 
} 
if( p == 51) 
{ 
str += "three "; 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
if( p == 52) 
{ 
str += "four "; 
} 
if( p == 53) 
{ 
str += "five "; 
} 
if( p == 54) 
{ 
str += "six "; 
} 
if( p == 55) 
{ 
str += "seven "; 
} 
if( p == 56) 
{ 
str += "eight "; 
} 
if( p == 57) 
{ 
str += "nine "; 
} 
} 
returnstr; 
} 
public static void main(String args[]) throws Exception 
{ 
ServerConverts1 = new ServerConvert(); 
Naming.bind("Wrd",s1); 
System.out.println("Object registered...."); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
3. ClientConvert.java 
importjava.rmi.*; 
importjava.io.*; 
public class ClientConvert 
{ 
public static void main(String args[]) throws Exception 
{ 
InterConverth1 = (InterConvert)Naming.lookup("Wrd"); 
BufferedReaderbr = new BufferedReader(new 
InputStreamReader(System.in)); 
System.out.println("Enter a number : t"); 
String no = br.readLine(); 
String ans = h1.convertDigit(no); 
System.out.println("The word representation of the entered digit is : " +ans); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: 
Fig 2.4 Client Window 
 
Fig 2.5: Server Window
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Fig 2.6: Client Convert Window
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Practical No: 03 
Aim: Show the implementation of Remote Procedure Call. 
Practical 3A: A program to implement simple calculator operations like addition, 
subtraction, multiplication and division. 
Code: 
1. RPCClient.java 
import java.io.*; 
import java.net.*; 
class RPCClient 
{ 
RPCClient() 
{ 
try 
{ 
InetAddress ia = InetAddress.getLocalHost(); 
DatagramSocket ds = new DatagramSocket(); 
DatagramSocket ds1 = new DatagramSocket(1300); 
System.out.println("nRPC Clientn"); 
System.out.println("Enter method name and parameter like add 3 4n"); 
while (true) 
{ 
BufferedReader br = new BufferedReader(new 
InputStreamReader(System.in)); 
String str = br.readLine();
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
byte b[] = str.getBytes(); 
DatagramPacket dp = new DatagramPacket(b,b.length,ia,1200); 
ds.send(dp); 
dp = new DatagramPacket(b,b.length); 
ds1.receive(dp); 
String s = new String(dp.getData(),0,dp.getLength()); 
System.out.println("nResult = " + s + "n"); 
} 
} 
catch (Exception e) 
{ 
e.printStackTrace(); 
} 
} 
public static void main(String[] args) 
{ 
new RPCClient(); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
2. RPCServer.java 
import java.util.*; 
import java.net.*; 
class RPCServer 
{ 
DatagramSocket ds; 
DatagramPacket dp; 
String str,methodName,result; 
int val1,val2; 
RPCServer() 
{ 
try 
{ 
ds=new DatagramSocket(1200); 
byte b[]=new byte[4096]; 
while(true) 
{ 
dp=new DatagramPacket(b,b.length); 
ds.receive(dp); 
str=new String(dp.getData(),0,dp.getLength()); 
if(str.equalsIgnoreCase("q")) 
{ 
System.exit(1); 
} 
else 
{
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
StringTokenizer st = new StringTokenizer(str," "); 
Sonali. Parab. 
int i=0; 
while(st.hasMoreTokens()) 
{ 
String token=st.nextToken(); 
methodName=token; 
val1 = Integer.parseInt(st.nextToken()); 
val2 = Integer.parseInt(st.nextToken()); 
} 
} 
System.out.println(str); 
InetAddress ia = InetAddress.getLocalHost(); 
if(methodName.equalsIgnoreCase("add")) 
{ 
result= "" + add(val1,val2); 
} 
dName.equalsIgnoreCase("sub")) 
{ 
result= "" + sub(val1,val2); 
} 
else if(methodName.equalsIgnoreCase("mul")) 
{ 
result= "" + mul(val1,val2); 
} 
else if(methodName.equalsIgnoreCase("div")) 
{
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
result= "" + div(val1,val2); 
} 
byte b1[]=result.getBytes(); 
DatagramSocket ds1 = new DatagramSocket(); 
DatagramPacket dp1 = new 
DatagramPacket(b1,b1.length,InetAddress.getLocalHost(), 1300); 
System.out.println("result : "+result+"n"); 
ds1.send(dp1); 
} 
} 
catch (Exception e) 
{ 
e.printStackTrace(); 
} 
} 
public int add(int val1, int val2) 
{ 
return val1+val2; 
} 
public int sub(int val3, int val4) 
{ 
return val3-val4; 
} 
public int mul(int val3, int val4) 
{ 
return val3*val4;
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
} 
public int div(int val3, int val4) 
{ 
return val3/val4; 
} 
public static void main(String[] args) 
{ 
new RPCServer(); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: Client 
Output: Server
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Practical 3 B: A program that finds the square, square root, cube and cube root of the 
entered number. 
Sonali. Parab. 
Code: RPCNumClient.java 
import java.io.*; 
import java.net.*; 
class RPCNumClient 
{ 
RPCNumClient() 
{ 
try 
{ 
InetAddress ia = InetAddress.getLocalHost(); 
DatagramSocket ds = new DatagramSocket(); 
DatagramSocket ds1 = new DatagramSocket(1300); 
System.out.println("nRPC Clientn"); 
System.out.println("1. Square of the number - squaren2. Square root 
of 
the number - squarerootn3. Cube of the number - cuben4. Cube root of the number - 
cuberoot"); 
System.out.println("Enter method name and the numbern"); 
while (true) 
{ 
BufferedReader br = new BufferedReader(new 
InputStreamReader(System.in)); 
String str = br.readLine(); 
byte b[] = str.getBytes(); 
DatagramPacket dp = new 
DatagramPacket(b,b.length,ia,1200); 
ds.send(dp); 
dp = new DatagramPacket(b,b.length); 
ds1.receive(dp); 
String s = new String(dp.getData(),0,dp.getLength()); 
System.out.println("nResult = " + s + "n"); 
} 
} 
catch (Exception e) 
{ 
e.printStackTrace(); 
} 
} 
public static void main(String[] args) 
{ 
new RPCNumClient(); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: Client 
Output: Server
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Practical No: 4 
Practical 4A: Implementing “Big” Web Service. 
1) Creating a Web Service 
A. Choosing a Container: 
1. Choose File > New Project. Select Web Application from the Java Web. 
2. Name the project CalculatorWSApplication. Select a location for the project. Click Next.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
3. Select your server and Java EE version and click Finish. 
B. Creating a Web Service from a Java Class 
1. Right-click the CalculatorWSApplication node and choose New > Web Service.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
2. Name the web service CalculatorWS and type org.me.calculator in Package. Leave Create 
Web Service from Scratch selected. If you are creating a Java EE 6 project on GlassFish or 
WebLogic, select Implement Web Service as a Stateless Session Bean. 
3. Click Finish. The Projects window displays the structure of the new web service and the 
source code is shown in the editor area. 
Sonali. Parab.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
2) Adding an Operation to the Web Service 
The goal of this exercise is to add to the web service an operation that adds two numbers 
received from a client. The NetBeans IDE provides a dialog for adding an operation to a web 
service. You can open this dialog either in the web service visual designer or in the web 
service context menu. 
A. To add an operation to the web service: 
1. Change to the Design view in the editor. 
2. Click Add Operation in either the visual designer or the context menu. The Add Operation 
dialog opens.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
3. In the upper part of the Add Operation dialog box, type add in Name and type int in the 
Return Type drop-down list. 
4. In the lower part of the Add Operation dialog box, click Add and create a parameter of 
type int named i. 
Sonali. Parab.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
5. Click Add again and create a parameter of type int called j. You now see the two integers 
as parameters. 
6. Click OK at the bottom of the Add Operation dialog box. You return to the editor. 
7. The visual designer now displays the following: 
Sonali. Parab.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
8. Click Source. And code the following. 
@WebMethod(operationName = "add") 
public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) 
{ 
int k = i + j; 
return k; 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
3) Deploying and Testing the Web Service 
After you deploy a web service to a server, you can use the IDE to open the server's test 
client, if the server has a test client. The GlassFish and WebLogic servers provide test clients. 
A. To test successful deployment to a GlassFish or WebLogic server: 
1. Right-click the project and choose Deploy. The IDE starts the application server, builds the 
application, and deploys the application to the server. 
2. In the IDE's Projects tab, expand the Web Services node of the CalculatorWSApplication 
project. Right-click the CalculatorWS node, and choose Test Web Service.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
3. The IDE opens the tester page in your browser, if you deployed a web application to the 
GlassFish server. 
4. If you deployed to the GlassFish server, type two numbers in the tester page, as shown 
below 
Sonali. Parab. 
5.Output
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
4) Consuming the Web Service 
Now that you have deployed the web service, you need to create a client to make use of the 
web service's add method. 
1. Client: Java Class in Java SE Application 
1. Choose File > New Project. Select Java Application from the Java category. Name the 
project CalculatorWS_Client_Application. Leave Create Main Class selected and accept all 
other default settings. Click Finish. 
2. Right-click the CalculatorWS_Client_Application node and choose New > Web Service 
Client. The New Web Service Client wizard opens. 
Sonali. Parab.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
3. Select Project as the WSDL source. Click Browse. Browse to the CalculatorWS web 
service in the CalculatorWSApplication project. When you have selected the web service, 
click OK. 
Sonali. Parab. 
4. Do not select a package name. Leave this field empty. 
5. Leave the other settings at default and click Finish. The Projects window displays the new 
web service client, with a node for the add method that you created:
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
6. Double-click your main class so that it opens in the Source Editor. Drag the add node 
below the main() method. 
You now see the following: 
public static void main(String[] args) 
{ 
Sonali. Parab. 
// TODO code application logic here 
} 
private static int add(int i, int j) 
{ 
org.me.calculator.CalculatorWS_Service service = new 
org.me.calculator.CalculatorWS_Service(); 
org.me.calculator.CalculatorWS port = service.getCalculatorWSPort(); 
return port.add(i, j); 
} 
7. In the main() method body, replace the TODO comment with code that initializes values 
for i and j, calls add(), and prints the result. 
public static void main(String[] args) 
{ 
int i = 13; 
int j =29; 
int result = add(i, j); 
System.out.println("Result = " + result); 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
8. Surround the main() method code with a try/catch block that prints an exception. 
Sonali. Parab. 
public static void main(String[] args) 
{ 
try 
{ 
int i = 13; 
int j = 29; 
int result = add(i, j); 
System.out.println("Result = " + result); 
} 
catch (Exception ex) 
{ 
System.out.println("Exception: " + ex); } 
} 
9. Right-click the project node and choose Run. 
The Output window now shows the sum: 
compile: 
run: 
Result = 42 
BUILD SUCCESSFUL (total time: 1 second)
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Practical 5B: Implementing Web Service that connects to MySQL database. 
Building Web Service:- 
 JAX-WS is an important part of the Java EE platform. 
 JAX-WS simplifies the task of developing Web services using Java technology. 
 It provides support for multiple protocols such as SOAP, XML and by providing a facility 
for supporting additional protocols along with HTTP. 
 With its support for annotations, JAX-WS simplifies Web service development and 
reduces the size of runtime files. 
 Here basic demonstration of using IDE to develop a JAX-WS Web Service is given. 
 After creating the web service, create web service clients that use the Web service over a 
network which is called consuming a web service. 
 The client is a servlet in a web application. 
 Let’s build a Web Service that returns the book name along with its cost for a particular 
ISBN. 
To begin building this service, create the data store. The server will access the data stored in a 
MySQL table to serve the client. 
1) Creating MySQL DB Table 
Type Following Queries in MySQL command line client window 
Create database bookshop ; 
Use bookshop;
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
 Create a table named Books that will store valid books information 
Type following queries in MySQL command line client to create table and describe them 
Create table books(isbn varchar(20),bookname varchar(20),bookprice varchar(20)); 
Desc bookshop; 
 Insert valid records in the Books table 
Type Insert Queries with suitable book names,prices and isbn numbers in command line 
client to enter valid book records 
Eg. Insert into books values(“123-456-042”,“Hitchhiker’s Guide to Galaxy”,”422”); 
2) Creating a web service
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
i. Choosing a container 
 Web service can be either deployed in a Web container or in an EJB container. 
 If a Java EE 6 application is created, use a Web container because EJBs can be placed 
directly in a Web application. 
ii. Creating a web application 
 To create a Web application, select File - New Project. 
 New Project dialog box appears. Select Java Web available under the Categories section 
and Web Application available under the Projects section. Click Next.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
 New Web Application dialog box appears. Enter BookWS as the project name in the 
Project Name textbox and select the option Use Dedicated Folder for Storing Libraries 
 New Web Service dialog box appears. Enter the name BookWS in the Web Service Name 
textbox, webservice in the Package textbox, select the option Create Web Service from 
scratch and also select the option implement web service as a stateless session bean as shown 
in the diagram. 
Sonali. Parab.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
 Click Finish. The Projects window displays the structure of the new web service and the 
Sonali. Parab. 
source code is shown in the editor area. 
i. Adding an operation to the web service 
 Change the source view of the BookWS.java to design view by clicking Design available 
just below the name of the BookWS.java tab. 
 The window changes as shown in the diagram.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Click Add Operation available in the design view of the web service. 
 Add Operation dialog appears. Enter the name getBookDetails in the Name textbox and 
java.lang.String in the Return Type textbox as shown in the diagram. 
 In Add Operation dialog box, click Add and create a parameter of the type String named 
isbn as shown in the diagram.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
 Click Ok. The design view displays the operation added as shown in the diagram. 
 Click Source. The code spec expands due to the operation added to the web service as 
Sonali. Parab. 
shown in the diagram 
Modify the code spec of the web service BookWS.java. 
Code Spec 
package webservice; 
import java.sql.*; 
import javax.jws.WebMethod; 
import javax.jws.WebParam; 
import javax.jws.WebService; 
import javax.ejb.Stateless; 
@WebService() 
@Stateless() 
public class BookWS { 
/** 
* Web service operation 
*/ 
@WebMethod(operationName = "getBookDetails") 
public String getBookDetails(@WebParam(name = "isbn") 
String isbn) { 
//TODO write your implementation code here: 
Connection dbcon = null;
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Statement stmt = null; 
ResultSet rs = null; 
String query = null; 
try 
{ 
Class.forName("com.mysql.jdbc.Driver").newInstance(); 
dbcon = DriverManager.getConnection("jdbc:mysql://localhost/bookshop","root","1"); 
stmt = dbcon.createStatement(); 
query = "select * from books where isbn = '" +isbn+ "'"; 
rs = stmt.executeQuery(query); 
rs.next(); 
String bookDetails = "<h1>The name of the book is <b>" +rs.getString("bookname") + "</b> 
and its cost is <b>" +rs.getString("bookprice") + "</b></h1>."; 
return bookDetails; 
} 
catch(Exception e) 
{ 
System.out.println("Sorry failed to connect to the database.." + e.getMessage()); 
} 
return null; 
} 
} 
Sonali. Parab.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
4) Adding the MySQL connector 
 We need to add a reference of MySQL connector to our web service. It is via this 
connector that our web service will be able to communicate with the database. 
 Right click on the libraries and select Add JAR/Folder as shown in the diagram. 
 Choose the location where mysql-coonector-java-5.1.10-bin is located, select it and click 
on open as shown.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
5) Deploying and testing the web service 
 When a web service is deployed to a web container, the IDE allows testing the web 
service to see if it functions as expected. 
 The tester application provided by GlassFish, is integrated into the IDE for this purpose 
as it allows the developer to enter values and test them. 
 No facility for testing whether an EJB module is deployed successfully is currently 
available. 
 To test the BookWS application, right click the BookWS project and select Deploy as 
shown in the diagram. 
The IDE starts the server, builds the application and deploys the application to the server. 
 Follow the progress of these operations in the BookWS (run-deploy) and GlassFish v3 
Domain tabs in the Output view.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
 Now expand the web services directory of the BookWS project, right-click the BookWS 
Sonali. Parab. 
Web service and select Test web service as shown in the diagram. 
 The IDE opens the tester page in the web browser, if the web application is deployed 
using GlassFish server as shown in the figure.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
 Enter the ISBN number as shown in the diagram. 
 Click getBookDetails. The book name and its cost are displayed as shown in the 
diagram.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
6) Consuming the web service 
 Once the web service is deployed, the next most logical step is to create a client to make 
use of the web service’s getBookDetails() method. 
 To create a web application, select File -> New Project. 
 New project dialog box appears, select java web available under the categories section 
and web application available under the projects section. Click Next.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
 New web application dialog box appears. Enter BookWSServletClient as the project 
name in the Project Name textbox and select the option Use Dedicated Folder for Storing 
Libraries. 
 Click Next. Server and settings section of the new web application, dialog box appears. 
Choose the default i.e. GlassFish v3 Domain as the web serevr, the Java EE 6 web as the 
Java EE version and the context path 
Sonali. Parab.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
 Click Finish. 
 The web application named BookWSServletClient is created. 
ii. Adding the web service to the client application 
 Right-click the BookWSServletClient project and select New -> Web Service Client as 
shown in the diagram.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
 New Web Service Client dialog box appears. In the Project section, click Browse and 
browse through the web service which needs to be consumed. Click ok. The name of the 
web service appears in the New Web Service Client as shown in the diagram. 
Sonali. Parab. 
 Leave the other settings as it is. Click Finish. 
 The Web Service Reference directory is added to the BookWSServletClient application 
as shown in the diagram. It displays the structure of the newly created client including the 
getBookDetails() method created earlier.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Creating a servlet 
 Create retreiveBookDetails.java using NetBeans IDE. 
 Right click source package directory, select New -> Servlet. 
 New Servlet dialog box appears. Enter retreiveBookDetails in the Class Name textbox 
and enter servlet in the package textbox.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
 Click Next. Configure Servlet Deployment section of the New Servlet dialog box appears. 
Sonali. Parab. 
Keep the defaults. 
 Click Finish. 
 This creates the servlet named retreiveBookDetails.java in the servlet package. 
 retreiveBookDetails.java is available with the default skeleton created by the NetBeans 
IDE which needs to be modified to hold the application logic. 

MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
 In the retreieveBookDetails.java source code, remove the following comments available 
Sonali. Parab. 
in the body of the processRequest() method. 
/*TODO output your page here*/ 
 Replace the following code spec: 
out.println("<h1>Servlet retreiveBookDetails at " + request.getContextPath () + "</h1>"); 
With the code spec of the getBookDetails() operation of the web service by dragging and 
dropping the getBookDetails operation as shown in the diagram. 
 Now change the following code spec: 
 Add this code 
out.println(getBookDetails(request.getParameter("isbn"))); 
to processRequest() method between 
out.println(“<body>”); and out.println(“</body>”)
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
iv. Creating an HTML form 
 Once the web service is added and the servlet is created, the form to accept ISBN from 
the user needs to be coded. 
 Since NetBeans IDE by default [as a part of Web Application creation] makes available 
index.jsp file. Modify it to hold the following code spec. 
<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>SOAP Cleint - Get Book Details</title> 
</head> 
<body bgcolor="white"> 
<form name="frmgetBookDetails" method="post" action="retreiveBookDetails"> 
<h1> 
ISBN : <input type="text" name="isbn"/><br><br> 
</h1> 
<input type="submit" value="Submit"/> 
</form> 
</body> 
</html>
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
V.Building the Web Application 
 Build the web application. 
 Right click BookWSServletClient project and select Build. 
 Once the Build menu item is clicked the details about the compilation and building of the 
BookWSServletClient Web application appears in the output – BookWSServletClient 
(dist) window.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
vi. Running the Application 
 Once the compilation and building of the web application is done run the application. 
 Right click the BookWSServerCleint project and select run. 
 Once the run processing completes in NetBeans IDE a web browser is automatically 
launched and the BookWSServletCleint application is executed as shown in the diagram.
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
PRACTICAL NO: 5 
Aim: Write a program to execute any one mutual exclusion algorithm. 
Code: 
1. Server.java 
import java.io.*; 
import java.net.*; 
class Server 
{ 
public static void main(String args[]) throws Exception 
{ 
ServerSocket ss=new ServerSocket(4722); 
System.out.println("Server is Started (listen mode) ...."); 
Socket s1 = ss.accept(); 
System.out.println("1st client connected ...."); 
BufferedReader br1 = new BufferedReader(new 
InputStreamReader(s1.getInputStream())); 
PrintStream ps1 = new PrintStream(s1.getOutputStream()); 
ps1.println("Hi client... connection established.. Enter commit or abort : "); 
ps1.flush(); 
Socket s2 = ss.accept();
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
System.out.println("2nd client connected ...."); 
BufferedReader br2 = new BufferedReader(new 
InputStreamReader(s2.getInputStream())); 
PrintStream ps2 = new PrintStream(s2.getOutputStream()); 
ps2.println("Hi client... connection established.. Enter commit or abort : "); 
ps2.flush(); 
String str1 = br1.readLine(); 
String str2 = br2.readLine(); 
if(str1.equalsIgnoreCase("commit") && str2.equalsIgnoreCase("commit")) 
{ 
System.out.println("1st client said : " + str1 ); 
System.out.println("2nd client said : " + str2 ); 
System.out.println("Result : doCommit"); 
ps1.println("Result : doCommit"); 
ps1.flush(); 
ps2.println("Result : doCommit"); 
ps2.flush(); 
} 
else 
{ 
System.out.println("1st client said : " + str1 ); 
System.out.println("2nd client said : " + str2 ); 
System.out.println("Result : doAbort"); 
ps1.println("Result : doAbort");
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
ps1.flush(); 
ps2.println("Result : doAbort"); 
ps2.flush(); 
} 
} 
} 
Code: 2. Cient1.java 
import java.io.*; 
import java.net.*; 
class Client1 
{ 
public static void main(String args[]) throws Exception 
{ 
BufferedReader brd = new BufferedReader(new 
InputStreamReader(System.in)); 
String serverMsg, clientMsg; 
Socket s=new Socket("localhost",4722); 
BufferedReader br = new BufferedReader(new 
InputStreamReader(s.getInputStream())); 
PrintStream ps = new PrintStream(s.getOutputStream());
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
serverMsg = br.readLine(); 
System.out.println(serverMsg); 
clientMsg = brd.readLine(); 
ps.println(clientMsg); 
ps.flush(); 
serverMsg = br.readLine(); 
System.out.println(serverMsg); 
} 
} 
Code: 3. Client2.java 
import java.io.*; 
import java.net.*; 
class Client2 
{ 
public static void main(String args[]) throws Exception 
{ 
BufferedReader brd = new BufferedReader(new 
InputStreamReader(System.in)); 
String serverMsg, clientMsg; 
Socket s=new Socket("localhost",4722);
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
BufferedReader br = new BufferedReader(new 
InputStreamReader(s.getInputStream())); 
PrintStream ps = new PrintStream(s.getOutputStream()); 
serverMsg = br.readLine(); 
System.out.println(serverMsg); 
clientMsg = brd.readLine(); 
ps.println(clientMsg); 
ps.flush(); 
serverMsg = br.readLine(); 
System.out.println(serverMsg); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: 
Fig 5.1 Server Window 
Fig 5.2 Client 1 Window
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Fig 5.3 Client 2 Window
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
PRACTICAL NO: 06 
Aim: Write a program to implement any one election algorithm 
Code: 
1. Election.c 
#include<stdio.h> 
#include<conio.h> 
#include<process.h> 
structproc 
{ 
int live; 
int identifier; 
} 
process[10]; 
intn,cordinator=1; 
/******************* DISPLAY PROCESSES **********************/ 
void display() 
{ 
int i; 
printf("n PROCESSES AREnn"); 
printf("Processes "); 
for(i=1;i<=n;i++) 
{ 
printf("P%dt",i); 
} 
printf("nlive ");
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
for(i=1;i<=n;i++) 
{ 
printf("%dt",process[i].live); 
} 
printf("nidentifier "); 
for(i=1;i<=n;i++) 
{ 
printf("%dt",process[i].identifier); 
} 
/***************** BULLY ALGORITH******************/ 
void bully() 
{ 
int ch,c,id,i=0,cordinator,init,max=-99; 
cordinator=i; 
for(i=1;i<=n;i++) 
{ 
if(process[cordinator].identifier<process[i].identifier&&process[i].live==1) 
cordinator=i; 
} 
printf("nn CURRENT CO-ORDINATOR IS=P%d",cordinator); 
while(ch!=4) 
{ 
printf("nnn *** BULLY ALGORITHM ***"); 
printf("n1.Crash a Processn2.Activate Processn3.Displayn4.Exit"); 
printf("nENTER UR CHOICE");
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
scanf("%d",&ch); 
switch(ch) 
{ 
case 1: 
printf("n Enter the process id to crash"); 
scanf("%d",&id); 
if(process[id].live==0) 
{ 
printf("n Already crashed process"); 
} 
else 
{ 
process[id].live=0; 
printf("n process P%d is crashed",id); 
if(id==cordinator) 
{ 
while(1) 
{ 
printf("n Enter process id who intiates election"); 
scanf("%d",&init); 
if(process[init].live==0) 
{ 
printf("n the selected process is crashed"); 
} 
else
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
{ 
for(i=1;i<=n;i++) 
{ 
if(i!=init&&& rocess[i].identifier>process[init].identifier) 
printf("n Election MSG sent from %d to %d",init,i); 
} 
for(i=1;i<=n;i++) 
{ 
if(i!=init) 
{ 
if(process[i].identifier>process[init].identifier&&process[i].live!=0) 
{ 
printf("n OK from %d to %d",i,init); 
} 
} 
} 
for(i=1;i<=n;i++) 
{ 
if(max<process[i].identifier && process[i].live!=0) 
{ 
cordinator=i; 
max=process[i].identifier; 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
printf("nn NEW CO-ORDINATOR 
IS=P%d",cordinator); 
break; 
} 
} 
} 
} 
break; 
case 2: 
printf("n Enter process id to activate"); 
scanf("%d",&id); 
if(process[id].live==1) 
{ 
printf("n Process %d is already active",id); 
} 
else 
{ 
process[id].live=1; 
printf("n Process %d activated",id); 
} 
if(process[id].identifier>process[cordinator].identifier) 
{ 
cordinator=id; 
printf("n NEW CO-ORDINATOR IS=P%dnn",id); 
} 
break;
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
case 3: 
display(); 
break; 
case 4: 
break; 
} 
} 
} 
/************ RING ALGORITHM ***************/ 
void ring() 
{ 
int ch,c,id,i=0,init,max=-99,last; 
for(i=1;i<=n;i++) 
{ 
if(process[cordinator].identifier<process[i].identifier&&process[i].live==1) 
cordinator=i; 
} 
printf("nn CURRENT CO-ORDINATOR IS=P%d",cordinator); 
while(ch!=4) 
{ 
printf("nnn *** RING ALGORITHM ***"); 
printf("n1.Crash a Processn2.Activate Processn3.Displayn4.Exit"); 
printf("nENTER UR CHOICE"); 
scanf("%d",&ch); 
switch(ch) 
{
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
case 1: 
printf("n Enter the process id to crash"); 
scanf("%d",&id); 
if(process[id].live==0) 
{ 
printf("n Already crashed process"); 
} 
else 
{ 
process[id].live=0; 
printf("n process P%d is crashed",id); 
if(id==cordinator) 
{ 
while(1) 
{ 
printf("n Enter process id who intiates election"); 
scanf("%d",&init); 
if(process[init].live==0) 
{ 
printf("n the selected process is crashed"); 
} 
else 
{ 
last=init; 
printf("nElection MSG sent from =%d",last);
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
for(i=init+1;i<=n;i++) 
{ 
if(i!=init) 
printf(" ->%d",i); 
} 
for(i=1;i<init;i++) 
{ 
if(i!=init) 
printf("->%d",i); 
last=i; 
} 
for(i=init+1;i<=n;i++) 
{ 
if(max<process[i].identifier && process[i].live==1) 
{ 
cordinator=i; 
max=process[i].identifier; 
} 
} 
for(i=1;i<=init;i++) 
{ 
if(max<process[i].identifier && process[i].live==1) 
{ 
cordinator=i; max=process[i].identifier; 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
} 
printf("nn NEW CO-ORDINATOR 
IS=P%d",cordinator); 
break; 
} 
} 
} 
} 
break; 
case 2: 
printf("n Enter process id to activate"); 
scanf("%d",&id); 
if(process[id].live==1) 
{ 
printf("n Process %d is already active",id); 
} 
else 
{ 
process[id].live=1; 
printf("n Process %d activated",id); 
if(process[id].identifier>process[cordinator].identifier) 
{ 
printf("n NEW CO-ORDINATOR IS=P%dnn",id); 
cordinator=id; 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
break; 
case 3: 
display(); 
break; 
case 4: 
break; 
} 
} 
} 
void main() 
{ 
intch,i,c; 
clrscr(); 
printf("n ENTER NO. OF PROCESSES"); 
scanf("%d",&n); 
for(i=1;i<=n;i++) 
{ 
printf("nEnterP%d process live or not(0/1)",i); 
scanf("%d",&process[i].live); 
printf("nEnterP%d process identifier",i); 
scanf("%d",&process[i].identifier); 
} 
display(); 
while(1) 
{ 
printf("nnn**** ELECTION ALGORITHM ****");
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
printf("n1.BULLY ALGORITHMn2.RING ALGORITHMn3.EXIT"); 
Sonali. Parab. 
printf("nn ENTER UR CHOICE"); 
scanf("%d",&ch); 
switch(ch) 
{ 
case 1: 
bully(); 
break; 
case 2: 
ring(); 
break; 
case 3: 
exit(0); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: 
Fig 6.1 Creating Processes 
Fig 6.2 List of Processes 
Fig 6.2 Algorithm Selection
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
1. Bully Algorithm 
Fig 6.1.1 Displaying Current Coordinator 
Fig 6.1.2 Operations of Bully Algorithm 
Fig 6.1.3 Crashing an Active Process 
Fig 6.1.4 Crashing a Crashed Process
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Fig 6.1.5 Activating a Crashed Process 
Fig 6.1.6 Activating Already Active Process 
Fig 6.1.7 Crashing the Co-ordinator and Election
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Fig 6.1.8 Displaying Process Status 
Fig 6.1.9 Exiting Bully Algorithm and Entering Main Menu
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
2. Ring Algorithm 
Fig 6.2.1 Displaying Co-ordinator 
Fig 6.2.2 Operations of Algorithm 
Fig 6.2.3 Crashing an Active Process 
Fig 6.2.4 Crashing an Already Crashed Process
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Fig 6.2.5 Activating a Crashed Process 
Fig 6.2.6 Activating already active Process 
Fig 6.2.7 Crashing the Co-ordinator and Election
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Fig 6.2.8 Displaying Process Status 
Fig 6.2.9 Exiting Ring Algorithm and Entering Main Menu
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Practical No: 07 
Aim: Show the implementation of any one clock synchronization algorithm. 
Code: 
1. SCServer.java 
import java.io.*; 
import java.net.*; 
import java.sql.*; 
public class SCServer 
{ 
public static void main(String args[])throws Exception 
{ 
InetAddress lclhost; 
lclhost=InetAddress.getLocalHost(); 
long maxtime,skewtime,datatime; 
String maxtimestr,skewtimestr; 
BufferedReader br; 
ClntServer ser=new ClntServer(lclhost); 
System.out.println("Enter the maximum time"); 
br = new BufferedReader(new InputStreamReader(System.in)); 
maxtimestr=br.readLine(); 
System.out.println("Enter the maximum skew time"); 
br = new BufferedReader(new InputStreamReader(System.in)); 
skewtimestr=br.readLine(); 
maxtime=Long.parseLong(maxtimestr);
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
skewtime=Long.parseLong(skewtimestr); 
while(true) 
{ 
datatime = System.currentTimeMillis(); 
long G = datatime-maxtime-skewtime; 
System.out.println("G ="+G); 
ser.setTimeStamp(new Timestamp(G)); 
ser.recPort(8001); 
ser.recData(); 
} 
} 
} 
class ClntServer 
{ 
InetAddress lclhost; 
int recport; 
Timestamp obtmp; 
ClntServer(InetAddress lclhost) 
{ 
this.lclhost = lclhost; 
} 
void recPort(int recport) 
{ 
this.recport = recport; 
} 
void setTimeStamp(Timestamp obtmp)
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
{ 
this.obtmp = obtmp; 
} 
void recData()throws Exception 
{ 
String msgstr=""; 
DatagramSocket ds; 
DatagramPacket dp; 
BufferedReader br; 
byte buf[] = new byte[256]; 
ds = new DatagramSocket(recport); 
dp = new DatagramPacket(buf,buf.length); 
ds.receive(dp); 
ds.close(); 
msgstr = new String(dp.getData(),0,dp.getLength()); 
System.out.println(msgstr); 
Timestamp obtmp = new Timestamp(Long.parseLong(msgstr)); 
if(this.obtmp.before(obtmp) == true) 
{ 
System.out.println("The Message is accepted"); 
} 
else 
{ 
System.out.println("The Message is rejected"); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
} 
2. SCClient.java 
import java.io.*; 
import java.net.*; 
public class SCClient 
{ 
public static void main(String args[])throws Exception 
{ 
InetAddress lclhost; 
lclhost=InetAddress.getLocalHost(); 
while(true) 
{ 
Client cntl=new Client(lclhost); 
cntl.sendPort(9001); 
cntl.sendData(); 
} 
} 
} 
class Client 
{ 
InetAddress lclhost; 
int senport; 
Client(InetAddress lclhost)
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
{ 
this.lclhost=lclhost; 
} 
void sendPort(int senport) 
{ 
this.senport=senport; 
} 
void sendData()throws Exception 
{ 
DatagramPacket dp; 
DatagramSocket ds; 
BufferedReader br; 
br=new BufferedReader(new InputStreamReader(System.in)); 
System.out.println("Enter the data"); 
String str=br.readLine(); 
ds = new DatagramSocket(senport); 
dp = new 
DatagramPacket(str.getBytes(),str.length(),lclhost,senport-1000); 
ds.send(dp); 
ds.close(); 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: 
Fig 7.1 Server Window 
Fig 7.2 Client Window
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Practical No: 08 
Aim: Write a program to implement two phase commit protocol. 
Code: 
1. Server.java 
import java.io.*; 
import java.net.*; 
import java.util.*; 
public class Server 
{ 
boolean closed=false,inputFromAll=false; 
List<clientThread> t; 
List<String> data; 
Server() 
{ 
t = new ArrayList<clientThread>(); 
data= new ArrayList<String>(); 
} 
public static void main(String args[]) 
{ 
Socket clientSocket = null; 
ServerSocket serverSocket = null; 
int port_number=1111;
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Server ser=new Server(); 
try 
{ 
serverSocket = new ServerSocket(port_number); 
} 
catch (IOException e) 
{ 
System.out.println(e); 
} 
while(!ser.closed) 
{ 
try 
{ 
clientSocket = serverSocket.accept(); 
clientThread th=new clientThread(ser,clientSocket); 
(ser.t).add(th); 
System.out.println("nNow Total clients are : 
"+(ser.t).size()); 
(ser.data).add("NOT_SENT"); 
th.start(); 
} 
catch (IOException e) 
{ 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
} 
try 
{ 
serverSocket.close(); 
} 
catch(Exception e1) 
{ 
} 
} 
} 
class clientThread extends Thread 
{ 
DataInputStream is = null; 
String line; 
String destClient=""; 
String name; 
PrintStream os = null; 
Socket clientSocket = null; 
String clientIdentity; 
Server ser; 
public clientThread(Server ser,Socket clientSocket) 
{ 
this.clientSocket=clientSocket; 
this.ser=ser;
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
} 
public void run() 
{ 
try 
{ 
is = new DataInputStream(clientSocket.getInputStream()); 
os = new PrintStream(clientSocket.getOutputStream()); 
os.println("Enter your name."); 
name = is.readLine(); 
clientIdentity=name; 
os.println("Welcome "+name+" to this 2 Phase 
Application.nYou will receive a vote Request now..."); 
os.println("VOTE_REQUESTnPlease enter COMMIT or 
ABORT to proceed : "); 
for(int i=0; i<(ser.t).size(); i++) 
{ 
if((ser.t).get(i)!=this) 
{ 
((ser.t).get(i)).os.println("---A new user 
"+name+" 
entered the Appilcation---"); 
} 
} 
while (true)
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
{ 
line = is.readLine(); 
if(line.equalsIgnoreCase("ABORT")) 
{ 
System.out.println("nFrom '"+clientIdentity+"' : 
ABORTnnSince aborted we will not wait for inputs 
from other clients."); 
System.out.println("nAborted...."); 
for(int i=0; i<(ser.t).size(); i++) 
{ 
((ser.t).get(i)).os.println("GLOBAL_ABORT"); 
((ser.t).get(i)).os.close(); 
((ser.t).get(i)).is.close(); 
} 
break; 
} 
if(line.equalsIgnoreCase("COMMIT")) 
{ 
System.out.println("nFrom '"+clientIdentity+"' : 
COMMIT"); 
if((ser.t).contains(this)) 
{ 
(ser.data).set((ser.t).indexOf(this), "COMMIT");
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
for(int j=0;j<(ser.data).size();j++) 
{ 
if(!(((ser.data).get(j)).equalsIgnoreCase("NOT 
SENT"))) 
{ 
ser.inputFromAll=true; 
continue; 
} 
else 
{ 
ser.inputFromAll=false; 
System.out.println("nWaiting for inputs 
from other clients."); 
break; 
} 
} 
if(ser.inputFromAll) 
{ 
System.out.println("nnCommited...."); 
for(int i=0; i<(ser.t).size(); i++) 
{ 
((ser.t).get(i)).os.println("GLOBAL_COMMIT" 
); 
((ser.t).get(i)).os.close(); 
((ser.t).get(i)).is.close();
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
} 
break; 
} 
}//if t.contains 
}//commit 
}//while 
ser.closed=true; 
clientSocket.close(); 
} 
catch(IOException e) 
{ 
}; 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
2. Client.java 
import java.io.*; 
import java.net.*; 
public class Client implements Runnable 
{ 
static Socket clientSocket = null; 
static PrintStream os = null; 
static DataInputStream is = null; 
static BufferedReader inputLine = null; 
static boolean closed = false; 
public static void main(String[] args) 
{ 
int port_number=1111; 
String host="localhost"; 
try 
{ 
clientSocket = new Socket(host, port_number); 
inputLine = new BufferedReader(new 
InputStreamReader(System.in)); 
os = new PrintStream(clientSocket.getOutputStream()); 
is = new DataInputStream(clientSocket.getInputStream()); 
} 
catch (Exception e)
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
{ 
System.out.println("Exception occurred : "+e.getMessage()); 
} 
if (clientSocket != null && os != null && is != null) 
{ 
try 
{ 
new Thread(new Client()).start(); 
while (!closed) 
{ 
os.println(inputLine.readLine()); 
} 
os.close(); 
is.close(); 
clientSocket.close(); 
} 
catch (IOException e) 
{ 
System.err.println("IOException: " + e); 
} 
} 
} 
public void run() 
{
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
String responseLine; 
try 
{ 
while ((responseLine = is.readLine()) != null) 
{ 
System.out.println("n"+responseLine); 
if (responseLine.equalsIgnoreCase("GLOBAL_COMMIT")==true 
|| 
responseLine.equalsIgnoreCase("GLOBAL_ABORT")==true ) 
{ 
break; 
} 
} 
closed=true; 
} 
catch (IOException e) 
{ 
System.err.println("IOException: " + e); 
} 
} 
}
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Output: 
Fig 8.1 Server Window 
Fig 8.2 Client Window 1
MSc IT Part – I, Semester-1 Page No:- ________ 
DISTRIBUTED SYSTEMS Date:- ____________ 
Sonali. Parab. 
Fig 8.3 Client Window 2

More Related Content

PDF
Java_practical_handbook
PDF
ikh331-06-distributed-programming
PDF
Writing Domain-Specific Languages for BeepBeep
PDF
Lecture6
PDF
Core java pract_sem iii
PDF
DCN Practical
PDF
Advanced Java Practical File
PDF
Indexing and Performance Tuning
Java_practical_handbook
ikh331-06-distributed-programming
Writing Domain-Specific Languages for BeepBeep
Lecture6
Core java pract_sem iii
DCN Practical
Advanced Java Practical File
Indexing and Performance Tuning

What's hot (20)

DOCX
DOCX
Java practical
ODP
Jersey Guice AOP
PPTX
分散式系統
DOCX
Java PRACTICAL file
PDF
MongoDB World 2016: Deciphering .explain() Output
PDF
Look Ma, “update DB to HTML5 using C++”, no hands! 
DOCX
Dotnet 18
PPT
Socket Programming
PDF
Silicon Valley JUG: JVM Mechanics
PDF
Concurrency Concepts in Java
PDF
Mattbrenner
PDF
Indexing and Query Optimizer (Mongo Austin)
PPTX
Lecture no 3
PPTX
High Data Availability and Consistency for Distributed Hash Tables Deployed ...
PPT
Thread
PDF
Application-Specific Models and Pointcuts using a Logic Meta Language
DOC
Final JAVA Practical of BCA SEM-5.
PPTX
Accelerating Habanero-Java Program with OpenCL Generation
Java practical
Jersey Guice AOP
分散式系統
Java PRACTICAL file
MongoDB World 2016: Deciphering .explain() Output
Look Ma, “update DB to HTML5 using C++”, no hands! 
Dotnet 18
Socket Programming
Silicon Valley JUG: JVM Mechanics
Concurrency Concepts in Java
Mattbrenner
Indexing and Query Optimizer (Mongo Austin)
Lecture no 3
High Data Availability and Consistency for Distributed Hash Tables Deployed ...
Thread
Application-Specific Models and Pointcuts using a Logic Meta Language
Final JAVA Practical of BCA SEM-5.
Accelerating Habanero-Java Program with OpenCL Generation
Ad

Viewers also liked (6)

PPT
Dist deadlock sureka
DOCX
Data Mining
PPSX
Election algorithms
PDF
Remote Method Invocation (RMI)
PDF
deadlock prevention
PPTX
Distributed DBMS - Unit 9 - Distributed Deadlock & Recovery
Dist deadlock sureka
Data Mining
Election algorithms
Remote Method Invocation (RMI)
deadlock prevention
Distributed DBMS - Unit 9 - Distributed Deadlock & Recovery
Ad

Similar to Distributed systems (20)

PDF
nw-lab_dns-server.pdf
DOCX
Laporan multi client
DOCX
network programing lab file ,
PPTX
#2 (UDP)
PDF
Networks lab
PDF
Networks lab
DOCX
Lab manual cn-2012-13
PDF
Laporan multiclient chatting client server
PDF
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
PPTX
Advance Java-Network Programming
PDF
java sockets
DOCX
Chatting dengan beberapa pc laptop
PDF
Advanced Java - Practical File
PPT
Ppt of socket
PPT
Networking & Socket Programming In Java
PPT
Chapter 4 slides
PDF
networks-lab-excercise4.pdf
PPTX
Networking in Python2025 (programs allll)
PPT
Network
PPT
Pemrograman Jaringan
nw-lab_dns-server.pdf
Laporan multi client
network programing lab file ,
#2 (UDP)
Networks lab
Networks lab
Lab manual cn-2012-13
Laporan multiclient chatting client server
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Advance Java-Network Programming
java sockets
Chatting dengan beberapa pc laptop
Advanced Java - Practical File
Ppt of socket
Networking & Socket Programming In Java
Chapter 4 slides
networks-lab-excercise4.pdf
Networking in Python2025 (programs allll)
Network
Pemrograman Jaringan

More from Sonali Parab (18)

PPT
Forensic laboratory setup requirements
DOCX
Forensic laboratory setup requirements
DOCX
Firewalls
DOCX
Embedded System
DOCX
Advance Database Management Systems -Object Oriented Principles In Database
PDF
Cloud and Ubiquitous Computing manual
PPT
Advance Database Management Systems -Object Oriented Principles In Database
PPT
Default and On demand routing - Advance Computer Networks
DOCX
Cloud Computing And Virtualization
DOCX
Protocols in Bluetooth
PPT
Protols used in bluetooth
PPT
Public Cloud Provider
DOCX
Public Cloud Provider
DOCX
Minning www
DOCX
Remote Method Invocation
DOCX
Agile testing
PPT
Minning WWW
PPTX
Remote Method Invocation (Java RMI)
Forensic laboratory setup requirements
Forensic laboratory setup requirements
Firewalls
Embedded System
Advance Database Management Systems -Object Oriented Principles In Database
Cloud and Ubiquitous Computing manual
Advance Database Management Systems -Object Oriented Principles In Database
Default and On demand routing - Advance Computer Networks
Cloud Computing And Virtualization
Protocols in Bluetooth
Protols used in bluetooth
Public Cloud Provider
Public Cloud Provider
Minning www
Remote Method Invocation
Agile testing
Minning WWW
Remote Method Invocation (Java RMI)

Recently uploaded (20)

PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Cell Structure & Organelles in detailed.
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
Classroom Observation Tools for Teachers
PDF
RMMM.pdf make it easy to upload and study
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Business Ethics Teaching Materials for college
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Basic Mud Logging Guide for educational purpose
Cell Structure & Organelles in detailed.
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
01-Introduction-to-Information-Management.pdf
Classroom Observation Tools for Teachers
RMMM.pdf make it easy to upload and study
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
VCE English Exam - Section C Student Revision Booklet
human mycosis Human fungal infections are called human mycosis..pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Business Ethics Teaching Materials for college
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Supply Chain Operations Speaking Notes -ICLT Program
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf

Distributed systems

  • 1. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. PRACTICAL NO:1 Aim: Write a program for implementing Client Server communication model. Practical 1 A A client server based program using TCP to find if the number entered is prime. Code: client.java importjava.net.*; importjava.io.*; class Client { public static void main(String args[]) { try{ Socket cs = new Socket("LocalHost",8001); BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a number : "); int a = Integer.parseInt(br.readLine()); DataOutputStream out = new DataOutputStream(cs.getOutputStream()); out.writeInt(a); DataInputStream in = new DataInputStream(cs.getInputStream()); System.out.println(in.readUTF()); cs.close(); } catch (Exception e) { System.out.println(e.toString()); } } }
  • 2. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Code: server.java importjava.net.*; importjava.io.*; class Server { public static void main(String args[]) { try{ ServerSocketss = new ServerSocket(8001); System.out.println("Server Running Succesfully... "); Socket s = ss.accept(); System.out.println("Client Request Accepted.."); DataInputStream in = new DataInputStream(s.getInputStream()); int x= in.readInt(); DataOutputStreamotc = new DataOutputStream(s.getOutputStream()); for(int i=2; i<=x; i++) { if(x%i==0) { if(i==x) otc.writeUTF(x + " is a Prime"); else otc.writeUTF(x + " is not a Prime"); break; } } } catch (Exception e) { System.out.println(e.toString()); } }
  • 3. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. } OUTPUT: Client Fig 1.1: Client Output OUTPUT: Server Fig 1.2: Server Output
  • 4. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Practical 1 B: A client server TCP based chatting application Code:ChatClient.java importjava.net.*; importjava.io.*; classChatClient { public static void main(String args[]) { try{ Socket s = new Socket("Localhost",8000); BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream out = new DataOutputStream(s.getOutputStream()); DataInputStream in = new DataInputStream(s.getInputStream()); String msg; System.out.println("To stop chatting with server type STOP"); System.out.print("Client Says: "); while((msg = br.readLine()) != null) { out.writeBytes(msg+"n"); if(msg.equals("STOP")) break; System.out.println("Server Says : "+in.readLine()); System.out.print("Client Says : "); } br.close(); in.close(); out.close(); s.close();
  • 5. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. } catch(Exception e) { e.printStackTrace(); } } }
  • 6. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Code:ChatServer.java importjava.net.*; importjava.io.*; classChatServer { public static void main(String args[]) { try{ ServerSocketss = new ServerSocket(8000); System.out.println("Waiting for client to connect.."); Socket s = ss.accept(); System.out.println("Client Connected"); BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream out = new DataOutputStream(s.getOutputStream()); DataInputStream in = new DataInputStream(s.getInputStream()); String receive, send; while((receive = in.readLine()) != null) { if(receive.equals("STOP")) break; System.out.println("Client Says : "+receive); System.out.print("Server Says : "); send = br.readLine(); out.writeBytes(send+"n"); } br.close(); in.close(); out.close();
  • 7. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. s.close(); } catch(Exception e) { e.printStackTrace(); } } }
  • 8. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. OUTPUT: Client Fig 1.3: Client Window OUTPUT: Server Fig 1.4: Server Window
  • 9. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Practical 1C: A client server based program using UDP to find if the number entered is evenor odd. Sonali. Parab. Code: udpClientEO.java importjava.io.*; importjava.net.*; public class udpClientEO { public static void main(String args[]) { try{ DatagramSocket ds = new DatagramSocket(1000); BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a number : "); String num = br.readLine(); byte b[] = new byte[1024]; b=num.getBytes(); DatagramPacketdp = new DatagramPacket(b,b.length,InetAddress.getLocalHost(),2000); ds.send(dp); byteb1[] = new byte[1024]; DatagramPacketdp1 = new DatagramPacket(b1,b1.length); ds.receive(dp1); String str = new String(dp1.getData(),0,dp1.getLength()); System.out.println(str); } catch(Exception e) { e.printStackTrace(); } } }
  • 10. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Code: udpServerEO.java importjava.io.*; importjava.net.*; public class udpServerEO { public static void main(String args[]) { try{ DatagramSocket ds = new DatagramSocket(2000); byte b[] = new byte[1024]; DatagramPacketdp = new DatagramPacket(b,b.length); ds.receive(dp); String str = new String(dp.getData(),0,dp.getLength()); System.out.println(str); int a= Integer.parseInt(str); String s= new String(); if (a%2 == 0) s = "Number is even"; else s = "Number is odd"; byteb1[] = new byte[1024]; b1 = s.getBytes(); DatagramPacketdp1 = new DatagramPacket(b1,b1.length,InetAddress.getLocalHost(),1000); ds.send(dp1); } catch(Exception e) { e.printStackTrace(); } } }
  • 11. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output : Client Fig 1.5: Client Window Output : Server Fig 1.6: Server Window
  • 12. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Practical 1D: A client server based program using UDP to find the factorial of the entered number. Sonali. Parab. Code: udpClientFact.java import java.io.*; import java.net.*; public class udpClientFact { public static void main(String args[]) { try{ DatagramSocket ds = new DatagramSocket(1000); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a number : "); String num = br.readLine(); byte b[] = new byte[1024];b=num.getBytes(); DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getLocalHost(),2000); ds.send(dp); byte b1[] = new byte[1024]; DatagramPacket dp1 = new DatagramPacket(b1,b1.length); ds.receive(dp1); String str = new String(dp1.getData(),0,dp1.getLength()); System.out.println(str); } catch(Exception e) { e.printStackTrace(); } }}
  • 13. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Code: udpServerFact.java import java.io.*; import java.net.*; public class udpServerFact { public static void main(String args[]){ try { DatagramSocket ds = new DatagramSocket(2000); byte b[] = new byte[1024]; DatagramPacket dp = new DatagramPacket(b,b.length); ds.receive(dp); String str = new String(dp.getData(),0,dp.getLength()); System.out.println(str); int a= Integer.parseInt(str); int f = 1, i; String s= new String(); for(i=1;i<=a;i++) f=f*i; s=Integer.toString(f); String str1 = "The Factorial of " + str + " is : " + f; byte b1[] = new byte[1024]; b1 = str1.getBytes(); DatagramPacket dp1 = new DatagramPacket(b1,b1.length,InetAddress.getLocalHost(),1000); ds.send(dp1); } catch(Exception e) { e.printStackTrace(); } } }
  • 14. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Client Fig 1.7: Client Output Output: Server Fig 1.8: Server Output
  • 15. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Practical 1E: A multicast Socket example. Code: BroadcastClient.java import java.net.*; import java.io.*; public class BroadcastClient { public static final int PORT = 1234; public static void main(String args[])throws Exception { MulticastSocket socket; DatagramPacket packet; InetAddress address; address = InetAddress.getByName("239.1.2.3"); socket = new MulticastSocket(PORT); //join a Multicast group and wait for a message socket.joinGroup(address); byte[] data = new byte[100]; packet = new DatagramPacket(data,data.length); for(;;) { // receive the packets socket.receive(packet); String str = new String(packet.getData()); System.out.println("Message received from "+ packet.getAddress() + " Message is : "+str); } } }
  • 16. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Code: BroadcastServer.java import java.net.*; import java.io.*; import java.util.*; public class BroadcastServer { public static final int PORT = 1234; public static void main(String args[])throws Exception { MulticastSocket socket; DatagramPacket packet; InetAddress address; address = InetAddress.getByName("239.1.2.3"); socket = new MulticastSocket(); // join a Multicast group and send the group messages socket.joinGroup(address); byte[] data = null; for(;;) { Thread.sleep(10000); System.out.println("Sending "); String str = ("This is Neha Calling "); data = str.getBytes(); packet = new DatagramPacket(data, str.length(),address,PORT); //Sends the packet socket.send(packet); } } }
  • 17. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Client Fig 1.9: Client Output Output: Server Fig 1.10: Server Output
  • 18. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. PRACTICAL NO: 2 Aim: Write a program to show the object communication using RMI. Practical 2A: A RMI based application program to display current date and time. Code: 1. InterDate.java importjava.rmi.*; public interface InterDate extends Remote { public String display() throws Exception; } 2. ServerDate.java importjava.rmi.*; importjava.rmi.server.*; importjava.util.*; public class ServerDate extends UnicastRemoteObject implements InterDate { publicServerDate() throws Exception { } public String display() throws Exception { String str = ""; Date d = new Date(); str = d.toString(); returnstr; } public static void main(String args[]) throws Exception { ServerDates1 = new ServerDate(); Naming.bind("DS",s1); System.out.println("Object registered....."); } }
  • 19. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 3. ClientDate.java importjava.rmi.*; importjava.io.*; public class ClientDate { public static void main(String args[]) throws Exception { String s1; InterDateh1 = (InterDate)Naming.lookup("DS"); s1 = h1.display(); System.out.println(s1); } }
  • 20. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Fig 2.1: Client Window Fig 2.2:Server Window
  • 21. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Fig 2.3: Client Window
  • 22. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Practical 2B: A RMI based application program that converts digits to words, e.g. 123 will be converted to one two three. Sonali. Parab. Code: 1. InterConvert.java importjava.rmi.*; public interface InterConvert extends Remote { public String convertDigit(String no) throws Exception; } 2. ServerConvert.java importjava.rmi.*; importjava.rmi.server.*; public class ServerConvert extends UnicastRemoteObject implements InterConvert { publicServerConvert() throws Exception { } public String convertDigit(String no) throws Exception { String str = ""; for(int i = 0; i <no.length(); i++) { int p = no.charAt(i); if( p == 48) { str += "zero "; } if( p == 49) { str += "one "; } if( p == 50) { str += "two "; } if( p == 51) { str += "three "; }
  • 23. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. if( p == 52) { str += "four "; } if( p == 53) { str += "five "; } if( p == 54) { str += "six "; } if( p == 55) { str += "seven "; } if( p == 56) { str += "eight "; } if( p == 57) { str += "nine "; } } returnstr; } public static void main(String args[]) throws Exception { ServerConverts1 = new ServerConvert(); Naming.bind("Wrd",s1); System.out.println("Object registered...."); } }
  • 24. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 3. ClientConvert.java importjava.rmi.*; importjava.io.*; public class ClientConvert { public static void main(String args[]) throws Exception { InterConverth1 = (InterConvert)Naming.lookup("Wrd"); BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a number : t"); String no = br.readLine(); String ans = h1.convertDigit(no); System.out.println("The word representation of the entered digit is : " +ans); } }
  • 25. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Fig 2.4 Client Window Fig 2.5: Server Window
  • 26. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Fig 2.6: Client Convert Window
  • 27. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Practical No: 03 Aim: Show the implementation of Remote Procedure Call. Practical 3A: A program to implement simple calculator operations like addition, subtraction, multiplication and division. Code: 1. RPCClient.java import java.io.*; import java.net.*; class RPCClient { RPCClient() { try { InetAddress ia = InetAddress.getLocalHost(); DatagramSocket ds = new DatagramSocket(); DatagramSocket ds1 = new DatagramSocket(1300); System.out.println("nRPC Clientn"); System.out.println("Enter method name and parameter like add 3 4n"); while (true) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine();
  • 28. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. byte b[] = str.getBytes(); DatagramPacket dp = new DatagramPacket(b,b.length,ia,1200); ds.send(dp); dp = new DatagramPacket(b,b.length); ds1.receive(dp); String s = new String(dp.getData(),0,dp.getLength()); System.out.println("nResult = " + s + "n"); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new RPCClient(); } }
  • 29. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 2. RPCServer.java import java.util.*; import java.net.*; class RPCServer { DatagramSocket ds; DatagramPacket dp; String str,methodName,result; int val1,val2; RPCServer() { try { ds=new DatagramSocket(1200); byte b[]=new byte[4096]; while(true) { dp=new DatagramPacket(b,b.length); ds.receive(dp); str=new String(dp.getData(),0,dp.getLength()); if(str.equalsIgnoreCase("q")) { System.exit(1); } else {
  • 30. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ StringTokenizer st = new StringTokenizer(str," "); Sonali. Parab. int i=0; while(st.hasMoreTokens()) { String token=st.nextToken(); methodName=token; val1 = Integer.parseInt(st.nextToken()); val2 = Integer.parseInt(st.nextToken()); } } System.out.println(str); InetAddress ia = InetAddress.getLocalHost(); if(methodName.equalsIgnoreCase("add")) { result= "" + add(val1,val2); } dName.equalsIgnoreCase("sub")) { result= "" + sub(val1,val2); } else if(methodName.equalsIgnoreCase("mul")) { result= "" + mul(val1,val2); } else if(methodName.equalsIgnoreCase("div")) {
  • 31. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. result= "" + div(val1,val2); } byte b1[]=result.getBytes(); DatagramSocket ds1 = new DatagramSocket(); DatagramPacket dp1 = new DatagramPacket(b1,b1.length,InetAddress.getLocalHost(), 1300); System.out.println("result : "+result+"n"); ds1.send(dp1); } } catch (Exception e) { e.printStackTrace(); } } public int add(int val1, int val2) { return val1+val2; } public int sub(int val3, int val4) { return val3-val4; } public int mul(int val3, int val4) { return val3*val4;
  • 32. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. } public int div(int val3, int val4) { return val3/val4; } public static void main(String[] args) { new RPCServer(); } }
  • 33. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Client Output: Server
  • 34. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Practical 3 B: A program that finds the square, square root, cube and cube root of the entered number. Sonali. Parab. Code: RPCNumClient.java import java.io.*; import java.net.*; class RPCNumClient { RPCNumClient() { try { InetAddress ia = InetAddress.getLocalHost(); DatagramSocket ds = new DatagramSocket(); DatagramSocket ds1 = new DatagramSocket(1300); System.out.println("nRPC Clientn"); System.out.println("1. Square of the number - squaren2. Square root of the number - squarerootn3. Cube of the number - cuben4. Cube root of the number - cuberoot"); System.out.println("Enter method name and the numbern"); while (true) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); byte b[] = str.getBytes(); DatagramPacket dp = new DatagramPacket(b,b.length,ia,1200); ds.send(dp); dp = new DatagramPacket(b,b.length); ds1.receive(dp); String s = new String(dp.getData(),0,dp.getLength()); System.out.println("nResult = " + s + "n"); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new RPCNumClient(); } }
  • 35. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Client Output: Server
  • 36. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Practical No: 4 Practical 4A: Implementing “Big” Web Service. 1) Creating a Web Service A. Choosing a Container: 1. Choose File > New Project. Select Web Application from the Java Web. 2. Name the project CalculatorWSApplication. Select a location for the project. Click Next.
  • 37. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 3. Select your server and Java EE version and click Finish. B. Creating a Web Service from a Java Class 1. Right-click the CalculatorWSApplication node and choose New > Web Service.
  • 38. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ 2. Name the web service CalculatorWS and type org.me.calculator in Package. Leave Create Web Service from Scratch selected. If you are creating a Java EE 6 project on GlassFish or WebLogic, select Implement Web Service as a Stateless Session Bean. 3. Click Finish. The Projects window displays the structure of the new web service and the source code is shown in the editor area. Sonali. Parab.
  • 39. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 2) Adding an Operation to the Web Service The goal of this exercise is to add to the web service an operation that adds two numbers received from a client. The NetBeans IDE provides a dialog for adding an operation to a web service. You can open this dialog either in the web service visual designer or in the web service context menu. A. To add an operation to the web service: 1. Change to the Design view in the editor. 2. Click Add Operation in either the visual designer or the context menu. The Add Operation dialog opens.
  • 40. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ 3. In the upper part of the Add Operation dialog box, type add in Name and type int in the Return Type drop-down list. 4. In the lower part of the Add Operation dialog box, click Add and create a parameter of type int named i. Sonali. Parab.
  • 41. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ 5. Click Add again and create a parameter of type int called j. You now see the two integers as parameters. 6. Click OK at the bottom of the Add Operation dialog box. You return to the editor. 7. The visual designer now displays the following: Sonali. Parab.
  • 42. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 8. Click Source. And code the following. @WebMethod(operationName = "add") public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) { int k = i + j; return k; }
  • 43. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 3) Deploying and Testing the Web Service After you deploy a web service to a server, you can use the IDE to open the server's test client, if the server has a test client. The GlassFish and WebLogic servers provide test clients. A. To test successful deployment to a GlassFish or WebLogic server: 1. Right-click the project and choose Deploy. The IDE starts the application server, builds the application, and deploys the application to the server. 2. In the IDE's Projects tab, expand the Web Services node of the CalculatorWSApplication project. Right-click the CalculatorWS node, and choose Test Web Service.
  • 44. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ 3. The IDE opens the tester page in your browser, if you deployed a web application to the GlassFish server. 4. If you deployed to the GlassFish server, type two numbers in the tester page, as shown below Sonali. Parab. 5.Output
  • 45. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ 4) Consuming the Web Service Now that you have deployed the web service, you need to create a client to make use of the web service's add method. 1. Client: Java Class in Java SE Application 1. Choose File > New Project. Select Java Application from the Java category. Name the project CalculatorWS_Client_Application. Leave Create Main Class selected and accept all other default settings. Click Finish. 2. Right-click the CalculatorWS_Client_Application node and choose New > Web Service Client. The New Web Service Client wizard opens. Sonali. Parab.
  • 46. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ 3. Select Project as the WSDL source. Click Browse. Browse to the CalculatorWS web service in the CalculatorWSApplication project. When you have selected the web service, click OK. Sonali. Parab. 4. Do not select a package name. Leave this field empty. 5. Leave the other settings at default and click Finish. The Projects window displays the new web service client, with a node for the add method that you created:
  • 47. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ 6. Double-click your main class so that it opens in the Source Editor. Drag the add node below the main() method. You now see the following: public static void main(String[] args) { Sonali. Parab. // TODO code application logic here } private static int add(int i, int j) { org.me.calculator.CalculatorWS_Service service = new org.me.calculator.CalculatorWS_Service(); org.me.calculator.CalculatorWS port = service.getCalculatorWSPort(); return port.add(i, j); } 7. In the main() method body, replace the TODO comment with code that initializes values for i and j, calls add(), and prints the result. public static void main(String[] args) { int i = 13; int j =29; int result = add(i, j); System.out.println("Result = " + result); }
  • 48. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ 8. Surround the main() method code with a try/catch block that prints an exception. Sonali. Parab. public static void main(String[] args) { try { int i = 13; int j = 29; int result = add(i, j); System.out.println("Result = " + result); } catch (Exception ex) { System.out.println("Exception: " + ex); } } 9. Right-click the project node and choose Run. The Output window now shows the sum: compile: run: Result = 42 BUILD SUCCESSFUL (total time: 1 second)
  • 49. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Practical 5B: Implementing Web Service that connects to MySQL database. Building Web Service:-  JAX-WS is an important part of the Java EE platform.  JAX-WS simplifies the task of developing Web services using Java technology.  It provides support for multiple protocols such as SOAP, XML and by providing a facility for supporting additional protocols along with HTTP.  With its support for annotations, JAX-WS simplifies Web service development and reduces the size of runtime files.  Here basic demonstration of using IDE to develop a JAX-WS Web Service is given.  After creating the web service, create web service clients that use the Web service over a network which is called consuming a web service.  The client is a servlet in a web application.  Let’s build a Web Service that returns the book name along with its cost for a particular ISBN. To begin building this service, create the data store. The server will access the data stored in a MySQL table to serve the client. 1) Creating MySQL DB Table Type Following Queries in MySQL command line client window Create database bookshop ; Use bookshop;
  • 50. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab.  Create a table named Books that will store valid books information Type following queries in MySQL command line client to create table and describe them Create table books(isbn varchar(20),bookname varchar(20),bookprice varchar(20)); Desc bookshop;  Insert valid records in the Books table Type Insert Queries with suitable book names,prices and isbn numbers in command line client to enter valid book records Eg. Insert into books values(“123-456-042”,“Hitchhiker’s Guide to Galaxy”,”422”); 2) Creating a web service
  • 51. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. i. Choosing a container  Web service can be either deployed in a Web container or in an EJB container.  If a Java EE 6 application is created, use a Web container because EJBs can be placed directly in a Web application. ii. Creating a web application  To create a Web application, select File - New Project.  New Project dialog box appears. Select Java Web available under the Categories section and Web Application available under the Projects section. Click Next.
  • 52. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________  New Web Application dialog box appears. Enter BookWS as the project name in the Project Name textbox and select the option Use Dedicated Folder for Storing Libraries  New Web Service dialog box appears. Enter the name BookWS in the Web Service Name textbox, webservice in the Package textbox, select the option Create Web Service from scratch and also select the option implement web service as a stateless session bean as shown in the diagram. Sonali. Parab.
  • 53. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________  Click Finish. The Projects window displays the structure of the new web service and the Sonali. Parab. source code is shown in the editor area. i. Adding an operation to the web service  Change the source view of the BookWS.java to design view by clicking Design available just below the name of the BookWS.java tab.  The window changes as shown in the diagram.
  • 54. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Click Add Operation available in the design view of the web service.  Add Operation dialog appears. Enter the name getBookDetails in the Name textbox and java.lang.String in the Return Type textbox as shown in the diagram.  In Add Operation dialog box, click Add and create a parameter of the type String named isbn as shown in the diagram.
  • 55. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________  Click Ok. The design view displays the operation added as shown in the diagram.  Click Source. The code spec expands due to the operation added to the web service as Sonali. Parab. shown in the diagram Modify the code spec of the web service BookWS.java. Code Spec package webservice; import java.sql.*; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.ejb.Stateless; @WebService() @Stateless() public class BookWS { /** * Web service operation */ @WebMethod(operationName = "getBookDetails") public String getBookDetails(@WebParam(name = "isbn") String isbn) { //TODO write your implementation code here: Connection dbcon = null;
  • 56. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Statement stmt = null; ResultSet rs = null; String query = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); dbcon = DriverManager.getConnection("jdbc:mysql://localhost/bookshop","root","1"); stmt = dbcon.createStatement(); query = "select * from books where isbn = '" +isbn+ "'"; rs = stmt.executeQuery(query); rs.next(); String bookDetails = "<h1>The name of the book is <b>" +rs.getString("bookname") + "</b> and its cost is <b>" +rs.getString("bookprice") + "</b></h1>."; return bookDetails; } catch(Exception e) { System.out.println("Sorry failed to connect to the database.." + e.getMessage()); } return null; } } Sonali. Parab.
  • 57. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 4) Adding the MySQL connector  We need to add a reference of MySQL connector to our web service. It is via this connector that our web service will be able to communicate with the database.  Right click on the libraries and select Add JAR/Folder as shown in the diagram.  Choose the location where mysql-coonector-java-5.1.10-bin is located, select it and click on open as shown.
  • 58. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 5) Deploying and testing the web service  When a web service is deployed to a web container, the IDE allows testing the web service to see if it functions as expected.  The tester application provided by GlassFish, is integrated into the IDE for this purpose as it allows the developer to enter values and test them.  No facility for testing whether an EJB module is deployed successfully is currently available.  To test the BookWS application, right click the BookWS project and select Deploy as shown in the diagram. The IDE starts the server, builds the application and deploys the application to the server.  Follow the progress of these operations in the BookWS (run-deploy) and GlassFish v3 Domain tabs in the Output view.
  • 59. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________  Now expand the web services directory of the BookWS project, right-click the BookWS Sonali. Parab. Web service and select Test web service as shown in the diagram.  The IDE opens the tester page in the web browser, if the web application is deployed using GlassFish server as shown in the figure.
  • 60. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab.  Enter the ISBN number as shown in the diagram.  Click getBookDetails. The book name and its cost are displayed as shown in the diagram.
  • 61. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 6) Consuming the web service  Once the web service is deployed, the next most logical step is to create a client to make use of the web service’s getBookDetails() method.  To create a web application, select File -> New Project.  New project dialog box appears, select java web available under the categories section and web application available under the projects section. Click Next.
  • 62. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________  New web application dialog box appears. Enter BookWSServletClient as the project name in the Project Name textbox and select the option Use Dedicated Folder for Storing Libraries.  Click Next. Server and settings section of the new web application, dialog box appears. Choose the default i.e. GlassFish v3 Domain as the web serevr, the Java EE 6 web as the Java EE version and the context path Sonali. Parab.
  • 63. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab.  Click Finish.  The web application named BookWSServletClient is created. ii. Adding the web service to the client application  Right-click the BookWSServletClient project and select New -> Web Service Client as shown in the diagram.
  • 64. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________  New Web Service Client dialog box appears. In the Project section, click Browse and browse through the web service which needs to be consumed. Click ok. The name of the web service appears in the New Web Service Client as shown in the diagram. Sonali. Parab.  Leave the other settings as it is. Click Finish.  The Web Service Reference directory is added to the BookWSServletClient application as shown in the diagram. It displays the structure of the newly created client including the getBookDetails() method created earlier.
  • 65. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Creating a servlet  Create retreiveBookDetails.java using NetBeans IDE.  Right click source package directory, select New -> Servlet.  New Servlet dialog box appears. Enter retreiveBookDetails in the Class Name textbox and enter servlet in the package textbox.
  • 66. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________  Click Next. Configure Servlet Deployment section of the New Servlet dialog box appears. Sonali. Parab. Keep the defaults.  Click Finish.  This creates the servlet named retreiveBookDetails.java in the servlet package.  retreiveBookDetails.java is available with the default skeleton created by the NetBeans IDE which needs to be modified to hold the application logic. 
  • 67. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________  In the retreieveBookDetails.java source code, remove the following comments available Sonali. Parab. in the body of the processRequest() method. /*TODO output your page here*/  Replace the following code spec: out.println("<h1>Servlet retreiveBookDetails at " + request.getContextPath () + "</h1>"); With the code spec of the getBookDetails() operation of the web service by dragging and dropping the getBookDetails operation as shown in the diagram.  Now change the following code spec:  Add this code out.println(getBookDetails(request.getParameter("isbn"))); to processRequest() method between out.println(“<body>”); and out.println(“</body>”)
  • 68. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. iv. Creating an HTML form  Once the web service is added and the servlet is created, the form to accept ISBN from the user needs to be coded.  Since NetBeans IDE by default [as a part of Web Application creation] makes available index.jsp file. Modify it to hold the following code spec. <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>SOAP Cleint - Get Book Details</title> </head> <body bgcolor="white"> <form name="frmgetBookDetails" method="post" action="retreiveBookDetails"> <h1> ISBN : <input type="text" name="isbn"/><br><br> </h1> <input type="submit" value="Submit"/> </form> </body> </html>
  • 69. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. V.Building the Web Application  Build the web application.  Right click BookWSServletClient project and select Build.  Once the Build menu item is clicked the details about the compilation and building of the BookWSServletClient Web application appears in the output – BookWSServletClient (dist) window.
  • 70. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. vi. Running the Application  Once the compilation and building of the web application is done run the application.  Right click the BookWSServerCleint project and select run.  Once the run processing completes in NetBeans IDE a web browser is automatically launched and the BookWSServletCleint application is executed as shown in the diagram.
  • 71. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. PRACTICAL NO: 5 Aim: Write a program to execute any one mutual exclusion algorithm. Code: 1. Server.java import java.io.*; import java.net.*; class Server { public static void main(String args[]) throws Exception { ServerSocket ss=new ServerSocket(4722); System.out.println("Server is Started (listen mode) ...."); Socket s1 = ss.accept(); System.out.println("1st client connected ...."); BufferedReader br1 = new BufferedReader(new InputStreamReader(s1.getInputStream())); PrintStream ps1 = new PrintStream(s1.getOutputStream()); ps1.println("Hi client... connection established.. Enter commit or abort : "); ps1.flush(); Socket s2 = ss.accept();
  • 72. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. System.out.println("2nd client connected ...."); BufferedReader br2 = new BufferedReader(new InputStreamReader(s2.getInputStream())); PrintStream ps2 = new PrintStream(s2.getOutputStream()); ps2.println("Hi client... connection established.. Enter commit or abort : "); ps2.flush(); String str1 = br1.readLine(); String str2 = br2.readLine(); if(str1.equalsIgnoreCase("commit") && str2.equalsIgnoreCase("commit")) { System.out.println("1st client said : " + str1 ); System.out.println("2nd client said : " + str2 ); System.out.println("Result : doCommit"); ps1.println("Result : doCommit"); ps1.flush(); ps2.println("Result : doCommit"); ps2.flush(); } else { System.out.println("1st client said : " + str1 ); System.out.println("2nd client said : " + str2 ); System.out.println("Result : doAbort"); ps1.println("Result : doAbort");
  • 73. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. ps1.flush(); ps2.println("Result : doAbort"); ps2.flush(); } } } Code: 2. Cient1.java import java.io.*; import java.net.*; class Client1 { public static void main(String args[]) throws Exception { BufferedReader brd = new BufferedReader(new InputStreamReader(System.in)); String serverMsg, clientMsg; Socket s=new Socket("localhost",4722); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintStream ps = new PrintStream(s.getOutputStream());
  • 74. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. serverMsg = br.readLine(); System.out.println(serverMsg); clientMsg = brd.readLine(); ps.println(clientMsg); ps.flush(); serverMsg = br.readLine(); System.out.println(serverMsg); } } Code: 3. Client2.java import java.io.*; import java.net.*; class Client2 { public static void main(String args[]) throws Exception { BufferedReader brd = new BufferedReader(new InputStreamReader(System.in)); String serverMsg, clientMsg; Socket s=new Socket("localhost",4722);
  • 75. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintStream ps = new PrintStream(s.getOutputStream()); serverMsg = br.readLine(); System.out.println(serverMsg); clientMsg = brd.readLine(); ps.println(clientMsg); ps.flush(); serverMsg = br.readLine(); System.out.println(serverMsg); } }
  • 76. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Fig 5.1 Server Window Fig 5.2 Client 1 Window
  • 77. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Fig 5.3 Client 2 Window
  • 78. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. PRACTICAL NO: 06 Aim: Write a program to implement any one election algorithm Code: 1. Election.c #include<stdio.h> #include<conio.h> #include<process.h> structproc { int live; int identifier; } process[10]; intn,cordinator=1; /******************* DISPLAY PROCESSES **********************/ void display() { int i; printf("n PROCESSES AREnn"); printf("Processes "); for(i=1;i<=n;i++) { printf("P%dt",i); } printf("nlive ");
  • 79. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. for(i=1;i<=n;i++) { printf("%dt",process[i].live); } printf("nidentifier "); for(i=1;i<=n;i++) { printf("%dt",process[i].identifier); } /***************** BULLY ALGORITH******************/ void bully() { int ch,c,id,i=0,cordinator,init,max=-99; cordinator=i; for(i=1;i<=n;i++) { if(process[cordinator].identifier<process[i].identifier&&process[i].live==1) cordinator=i; } printf("nn CURRENT CO-ORDINATOR IS=P%d",cordinator); while(ch!=4) { printf("nnn *** BULLY ALGORITHM ***"); printf("n1.Crash a Processn2.Activate Processn3.Displayn4.Exit"); printf("nENTER UR CHOICE");
  • 80. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. scanf("%d",&ch); switch(ch) { case 1: printf("n Enter the process id to crash"); scanf("%d",&id); if(process[id].live==0) { printf("n Already crashed process"); } else { process[id].live=0; printf("n process P%d is crashed",id); if(id==cordinator) { while(1) { printf("n Enter process id who intiates election"); scanf("%d",&init); if(process[init].live==0) { printf("n the selected process is crashed"); } else
  • 81. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. { for(i=1;i<=n;i++) { if(i!=init&&& rocess[i].identifier>process[init].identifier) printf("n Election MSG sent from %d to %d",init,i); } for(i=1;i<=n;i++) { if(i!=init) { if(process[i].identifier>process[init].identifier&&process[i].live!=0) { printf("n OK from %d to %d",i,init); } } } for(i=1;i<=n;i++) { if(max<process[i].identifier && process[i].live!=0) { cordinator=i; max=process[i].identifier; } }
  • 82. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. printf("nn NEW CO-ORDINATOR IS=P%d",cordinator); break; } } } } break; case 2: printf("n Enter process id to activate"); scanf("%d",&id); if(process[id].live==1) { printf("n Process %d is already active",id); } else { process[id].live=1; printf("n Process %d activated",id); } if(process[id].identifier>process[cordinator].identifier) { cordinator=id; printf("n NEW CO-ORDINATOR IS=P%dnn",id); } break;
  • 83. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. case 3: display(); break; case 4: break; } } } /************ RING ALGORITHM ***************/ void ring() { int ch,c,id,i=0,init,max=-99,last; for(i=1;i<=n;i++) { if(process[cordinator].identifier<process[i].identifier&&process[i].live==1) cordinator=i; } printf("nn CURRENT CO-ORDINATOR IS=P%d",cordinator); while(ch!=4) { printf("nnn *** RING ALGORITHM ***"); printf("n1.Crash a Processn2.Activate Processn3.Displayn4.Exit"); printf("nENTER UR CHOICE"); scanf("%d",&ch); switch(ch) {
  • 84. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. case 1: printf("n Enter the process id to crash"); scanf("%d",&id); if(process[id].live==0) { printf("n Already crashed process"); } else { process[id].live=0; printf("n process P%d is crashed",id); if(id==cordinator) { while(1) { printf("n Enter process id who intiates election"); scanf("%d",&init); if(process[init].live==0) { printf("n the selected process is crashed"); } else { last=init; printf("nElection MSG sent from =%d",last);
  • 85. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. for(i=init+1;i<=n;i++) { if(i!=init) printf(" ->%d",i); } for(i=1;i<init;i++) { if(i!=init) printf("->%d",i); last=i; } for(i=init+1;i<=n;i++) { if(max<process[i].identifier && process[i].live==1) { cordinator=i; max=process[i].identifier; } } for(i=1;i<=init;i++) { if(max<process[i].identifier && process[i].live==1) { cordinator=i; max=process[i].identifier; }
  • 86. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. } printf("nn NEW CO-ORDINATOR IS=P%d",cordinator); break; } } } } break; case 2: printf("n Enter process id to activate"); scanf("%d",&id); if(process[id].live==1) { printf("n Process %d is already active",id); } else { process[id].live=1; printf("n Process %d activated",id); if(process[id].identifier>process[cordinator].identifier) { printf("n NEW CO-ORDINATOR IS=P%dnn",id); cordinator=id; } }
  • 87. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. break; case 3: display(); break; case 4: break; } } } void main() { intch,i,c; clrscr(); printf("n ENTER NO. OF PROCESSES"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("nEnterP%d process live or not(0/1)",i); scanf("%d",&process[i].live); printf("nEnterP%d process identifier",i); scanf("%d",&process[i].identifier); } display(); while(1) { printf("nnn**** ELECTION ALGORITHM ****");
  • 88. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ printf("n1.BULLY ALGORITHMn2.RING ALGORITHMn3.EXIT"); Sonali. Parab. printf("nn ENTER UR CHOICE"); scanf("%d",&ch); switch(ch) { case 1: bully(); break; case 2: ring(); break; case 3: exit(0); } } }
  • 89. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Fig 6.1 Creating Processes Fig 6.2 List of Processes Fig 6.2 Algorithm Selection
  • 90. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 1. Bully Algorithm Fig 6.1.1 Displaying Current Coordinator Fig 6.1.2 Operations of Bully Algorithm Fig 6.1.3 Crashing an Active Process Fig 6.1.4 Crashing a Crashed Process
  • 91. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Fig 6.1.5 Activating a Crashed Process Fig 6.1.6 Activating Already Active Process Fig 6.1.7 Crashing the Co-ordinator and Election
  • 92. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Fig 6.1.8 Displaying Process Status Fig 6.1.9 Exiting Bully Algorithm and Entering Main Menu
  • 93. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 2. Ring Algorithm Fig 6.2.1 Displaying Co-ordinator Fig 6.2.2 Operations of Algorithm Fig 6.2.3 Crashing an Active Process Fig 6.2.4 Crashing an Already Crashed Process
  • 94. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Fig 6.2.5 Activating a Crashed Process Fig 6.2.6 Activating already active Process Fig 6.2.7 Crashing the Co-ordinator and Election
  • 95. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Fig 6.2.8 Displaying Process Status Fig 6.2.9 Exiting Ring Algorithm and Entering Main Menu
  • 96. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Practical No: 07 Aim: Show the implementation of any one clock synchronization algorithm. Code: 1. SCServer.java import java.io.*; import java.net.*; import java.sql.*; public class SCServer { public static void main(String args[])throws Exception { InetAddress lclhost; lclhost=InetAddress.getLocalHost(); long maxtime,skewtime,datatime; String maxtimestr,skewtimestr; BufferedReader br; ClntServer ser=new ClntServer(lclhost); System.out.println("Enter the maximum time"); br = new BufferedReader(new InputStreamReader(System.in)); maxtimestr=br.readLine(); System.out.println("Enter the maximum skew time"); br = new BufferedReader(new InputStreamReader(System.in)); skewtimestr=br.readLine(); maxtime=Long.parseLong(maxtimestr);
  • 97. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. skewtime=Long.parseLong(skewtimestr); while(true) { datatime = System.currentTimeMillis(); long G = datatime-maxtime-skewtime; System.out.println("G ="+G); ser.setTimeStamp(new Timestamp(G)); ser.recPort(8001); ser.recData(); } } } class ClntServer { InetAddress lclhost; int recport; Timestamp obtmp; ClntServer(InetAddress lclhost) { this.lclhost = lclhost; } void recPort(int recport) { this.recport = recport; } void setTimeStamp(Timestamp obtmp)
  • 98. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. { this.obtmp = obtmp; } void recData()throws Exception { String msgstr=""; DatagramSocket ds; DatagramPacket dp; BufferedReader br; byte buf[] = new byte[256]; ds = new DatagramSocket(recport); dp = new DatagramPacket(buf,buf.length); ds.receive(dp); ds.close(); msgstr = new String(dp.getData(),0,dp.getLength()); System.out.println(msgstr); Timestamp obtmp = new Timestamp(Long.parseLong(msgstr)); if(this.obtmp.before(obtmp) == true) { System.out.println("The Message is accepted"); } else { System.out.println("The Message is rejected"); } }
  • 99. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. } 2. SCClient.java import java.io.*; import java.net.*; public class SCClient { public static void main(String args[])throws Exception { InetAddress lclhost; lclhost=InetAddress.getLocalHost(); while(true) { Client cntl=new Client(lclhost); cntl.sendPort(9001); cntl.sendData(); } } } class Client { InetAddress lclhost; int senport; Client(InetAddress lclhost)
  • 100. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. { this.lclhost=lclhost; } void sendPort(int senport) { this.senport=senport; } void sendData()throws Exception { DatagramPacket dp; DatagramSocket ds; BufferedReader br; br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the data"); String str=br.readLine(); ds = new DatagramSocket(senport); dp = new DatagramPacket(str.getBytes(),str.length(),lclhost,senport-1000); ds.send(dp); ds.close(); } }
  • 101. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Fig 7.1 Server Window Fig 7.2 Client Window
  • 102. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Practical No: 08 Aim: Write a program to implement two phase commit protocol. Code: 1. Server.java import java.io.*; import java.net.*; import java.util.*; public class Server { boolean closed=false,inputFromAll=false; List<clientThread> t; List<String> data; Server() { t = new ArrayList<clientThread>(); data= new ArrayList<String>(); } public static void main(String args[]) { Socket clientSocket = null; ServerSocket serverSocket = null; int port_number=1111;
  • 103. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Server ser=new Server(); try { serverSocket = new ServerSocket(port_number); } catch (IOException e) { System.out.println(e); } while(!ser.closed) { try { clientSocket = serverSocket.accept(); clientThread th=new clientThread(ser,clientSocket); (ser.t).add(th); System.out.println("nNow Total clients are : "+(ser.t).size()); (ser.data).add("NOT_SENT"); th.start(); } catch (IOException e) { }
  • 104. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. } try { serverSocket.close(); } catch(Exception e1) { } } } class clientThread extends Thread { DataInputStream is = null; String line; String destClient=""; String name; PrintStream os = null; Socket clientSocket = null; String clientIdentity; Server ser; public clientThread(Server ser,Socket clientSocket) { this.clientSocket=clientSocket; this.ser=ser;
  • 105. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. } public void run() { try { is = new DataInputStream(clientSocket.getInputStream()); os = new PrintStream(clientSocket.getOutputStream()); os.println("Enter your name."); name = is.readLine(); clientIdentity=name; os.println("Welcome "+name+" to this 2 Phase Application.nYou will receive a vote Request now..."); os.println("VOTE_REQUESTnPlease enter COMMIT or ABORT to proceed : "); for(int i=0; i<(ser.t).size(); i++) { if((ser.t).get(i)!=this) { ((ser.t).get(i)).os.println("---A new user "+name+" entered the Appilcation---"); } } while (true)
  • 106. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. { line = is.readLine(); if(line.equalsIgnoreCase("ABORT")) { System.out.println("nFrom '"+clientIdentity+"' : ABORTnnSince aborted we will not wait for inputs from other clients."); System.out.println("nAborted...."); for(int i=0; i<(ser.t).size(); i++) { ((ser.t).get(i)).os.println("GLOBAL_ABORT"); ((ser.t).get(i)).os.close(); ((ser.t).get(i)).is.close(); } break; } if(line.equalsIgnoreCase("COMMIT")) { System.out.println("nFrom '"+clientIdentity+"' : COMMIT"); if((ser.t).contains(this)) { (ser.data).set((ser.t).indexOf(this), "COMMIT");
  • 107. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. for(int j=0;j<(ser.data).size();j++) { if(!(((ser.data).get(j)).equalsIgnoreCase("NOT SENT"))) { ser.inputFromAll=true; continue; } else { ser.inputFromAll=false; System.out.println("nWaiting for inputs from other clients."); break; } } if(ser.inputFromAll) { System.out.println("nnCommited...."); for(int i=0; i<(ser.t).size(); i++) { ((ser.t).get(i)).os.println("GLOBAL_COMMIT" ); ((ser.t).get(i)).os.close(); ((ser.t).get(i)).is.close();
  • 108. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. } break; } }//if t.contains }//commit }//while ser.closed=true; clientSocket.close(); } catch(IOException e) { }; } }
  • 109. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. 2. Client.java import java.io.*; import java.net.*; public class Client implements Runnable { static Socket clientSocket = null; static PrintStream os = null; static DataInputStream is = null; static BufferedReader inputLine = null; static boolean closed = false; public static void main(String[] args) { int port_number=1111; String host="localhost"; try { clientSocket = new Socket(host, port_number); inputLine = new BufferedReader(new InputStreamReader(System.in)); os = new PrintStream(clientSocket.getOutputStream()); is = new DataInputStream(clientSocket.getInputStream()); } catch (Exception e)
  • 110. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. { System.out.println("Exception occurred : "+e.getMessage()); } if (clientSocket != null && os != null && is != null) { try { new Thread(new Client()).start(); while (!closed) { os.println(inputLine.readLine()); } os.close(); is.close(); clientSocket.close(); } catch (IOException e) { System.err.println("IOException: " + e); } } } public void run() {
  • 111. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. String responseLine; try { while ((responseLine = is.readLine()) != null) { System.out.println("n"+responseLine); if (responseLine.equalsIgnoreCase("GLOBAL_COMMIT")==true || responseLine.equalsIgnoreCase("GLOBAL_ABORT")==true ) { break; } } closed=true; } catch (IOException e) { System.err.println("IOException: " + e); } } }
  • 112. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Output: Fig 8.1 Server Window Fig 8.2 Client Window 1
  • 113. MSc IT Part – I, Semester-1 Page No:- ________ DISTRIBUTED SYSTEMS Date:- ____________ Sonali. Parab. Fig 8.3 Client Window 2