Distributed SystemsLab
Distributed SystemsLab
1. Develop an FTP Client. Provide a GUI interface for the access of all the services. 2. Implement a mini DNS protocol using RPC. 3. Implement a chat server using JAVA. 4. Implement a 2PC for distributed transaction management. 5. Study of NFS.
1211111111;lklklk
1311111111;lklklk
AIM: To create TCP Sockets for C/S Communication HARDWARE REQUIREMENTS: Pentium 4 Processor, 256 MB RAM, 40GB HDD SOFTWARE REQUIREMENTS: JDK 1.5,JRE 1.5, J2SE 5.0 API and Redhat Server
DESCRIPTION: TCP sockets are connection oriented and provide reliable communication. In java TCP sockets are created by using ServerSocket and Socket classes in java.net package.
SOURCE CODE: TcpServer.java import java.io.*; import java.net.*; class TcpServer { public static void main(String[] args) throws Exception { ServerSocket ss=new ServerSocket(1600); while (true) { System.out.println("server is ready!"); Socket ls=ss.accept(); //READING DATA FROM CLIENT InputStream is=ls.getInputStream(); byte data[]=new byte[50]; is.read(data); String mfc=new String(data); mfc=mfc.trim(); String mfs="hello:"+mfc; //SENDING MESS TO CLIENT OutputStream os=ls.getOutputStream(); os.write(mfs.getBytes()); } }
1411111111;lklklk
4 } TcpClient .java import java.net.*; import java.io.*; class TcpClient { public static void main(String[] args) throws Exception { Socket cs=new Socket("localhost",1600); System.out.println("connecting to server!"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter u r name"); String n=br.readLine(); //SENDING DATA TO SERVER OutputStream os=cs.getOutputStream(); os.write(n.getBytes()); //READING DATA FROM SERVER InputStream is=cs.getInputStream(); byte data[]=new byte[50]; is.read(data); //PRINTING MESS AT CLIENT CONSLOE String mfs=new String(data); mfs=mfs.trim(); System.out.println(mfs); } } Output:
1511111111;lklklk
AIM: Java Program to create TCP Sockets for C/S Communication HARDWARE REQUIREMENTS: Pentium 4 Processor, 256 MB RAM, 40GB HDD SOFTWARE REQUIREMENTS: JDK 1.5,JRE 1.5, J2SE 5.0 API and Redhat Server
DESCRIPTION: UDP sockets are connection less and provide un reliable communication. In java UDP sockets are created by using DatagramSocket classe in java.net package.
SOURCE CODE: DatagrmServerApp.java import java.net.*; class DatagrmServerApp { public static int sp=997; public static int cp=998; public static int bs=1024; public static DatagramSocket ds; public static byte buff[]=new byte[bs]; public static void server() throws Exception { int pos=0; while (true) int c=System.in.read(); { switch (c) {
case '\n': ds.send(new DatagramPacket(buff,pos,InetAddress.getLocalHost(),cp)); pos=0; default: buff[pos++]=(byte)c; }} public static void main(String[] args) throws Exception { ds=new DatagramSocket(sp); server(); } } }
1611111111;lklklk
6 DgClient.java import java.net.*; class DgClient { public static int sp=997; public static int cp=998; public static int bs=1024; public static DatagramSocket ds; public static byte buff[]=new byte[bs]; public static void client() throws Exception { while (true) { DatagramPacket p=new DatagramPacket(buff,buff.length); ds.receive(p); System.out.println(new String(p.getData(),0,p.getLength())); } } public static void { main(String[] args) throws Exception }}
Output:
1711111111;lklklk
AIM: Provide Graphical User Interface for FTP Upload Service and Download Service
HARDWARE REQUIREMENTS: Pentium 4 Processor, 256 MB RAM, 40GB HDD SOFTWARE REQUIREMENTS: JDK 1.5,JRE 1.5, J2SE 5.0 API and Redhat Server
DESCRIPTION: FTP is a file transfer protocol which provides services like upload and download a file. Upload Service: File will be selected from local drive and store in server directory Download Service: File will be selected from remote machine and stored in client directory SOURCE CODE:
FTPClientGUI.java import javax.swing.*;import java.awt.*; import java.awt.event.*;import java.net.*; import java.io.*; class One extends JFrame implements ActionListener { public JButton b,b1; public JLabel l;public JLabel l1,lmsg1,lmsg2; One() { b=new JButton("Upload"); l=new JLabel("Upload a file : "); lmsg1=new JLabel(""); b1=new JButton("Download");l1=new JLabel("Download a file"); lmsg2=new JLabel("");setLayout(new GridLayout(2,3,10,10)); add(l);add(b);add(lmsg1);add(l1);add(b1);add(lmsg2); b.addActionListener(this);b1.addActionListener(this);setVisible(true); setSize(600,500);} public void actionPerformed(ActionEvent e) { String s=e.getActionCommand(); if(s.equals("Upload")) {JFileChooser j=new JFileChooser(); int val; val=j.showOpenDialog(One.this); lmsg1.setText("is uploaded");//s.close();
1811111111;lklklk
8 repaint();} if (b1.getModel().isArmed()) {lmsg2.setText( "is downlaoded");repaint(); }}} public class FTPClientGUI { public static void main(String[] args) { new One(); } }
Output:
1911111111;lklklk
DESCRIPTION: FTP is a file transfer protocol which provides services like upload and download a file. Upload Service: File will be selected from local drive and store in server directory Download Service: File will be selected from remote machine and stored in client directory SOURCE CODE: FTPClientGUIModified.java import javax.swing.*;import java.awt.*; import java.awt.event.*;import java.net.*; import java.io.*; class One extends JFrame implements ActionListener { public JButton b,b1; public JLabel l;public JLabel l1,lmsg1,lmsg2; One() { b=new JButton("Upload"); l=new JLabel("Upload a file : "); lmsg1=new JLabel(""); b1=new JButton("Download"); l1=new JLabel("Download a file"); lmsg2=new JLabel(""); b.setBounds(100, 20, 100, 25); b1.setBounds(100, 75, 100, 25); l.setBounds(5, 20, 100, 25); l1.setBounds(5, 75, 100, 25); setLayout(null); add(l);add(b);add(lmsg1);add(l1);add(b1);add(lmsg2); b.addActionListener(this);b1.addActionListener(this); setVisible(true); setSize(300,150);
11011111111;lklklk
10 setResizable(false); setDefaultCloseOperation(3); } public void actionPerformed(ActionEvent e) { String s=e.getActionCommand(); if(s.equals("Upload")) { JFileChooser j=new JFileChooser(); int val; val=j.showOpenDialog(One.this); lmsg1.setText("is uploaded"); //s.close(); repaint(); } if (b1.getModel().isArmed()) { lmsg2.setText( "is downlaoded"); repaint(); } } } public class FTPClientGUIModified { public static void main(String[] args) { new One(); } }
11111111111;lklklk
11 Output:
11211111111;lklklk
12
5. Develop an FTP Client. Provide a GUI interface for the access upload and download services.
AIM: Develop an FTP Client to provide upload and download services. HARDWARE REQUIREMENTS: Pentium 4 Processor, 256 MB RAM, 40GB HDD SOFTWARE REQUIREMENTS: JDK 1.5,JRE 1.5, J2SE 5.0 API and Redhat Server
DESCRIPTION: Upload Service: File will be selected from local drive and store in server directory Download Service: File will be selected from remote machine and stored in client directory SOURCE CODE: FTPServer.java import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class FTPServer { public static void main(String[] args) { try { while (true) { ServerSocket ss=new ServerSocket(1010); Socket sl=ss.accept(); System.out.println("Server scoket is created...."); System.out.println(" test1"); DataInputStream fromserver=new DataInputStream(sl.getInputStream()); System.out.println(" test2"); String option=fromserver.readLine(); if (option.equalsIgnoreCase("upload")) { System.out.println("upload test"); String filefromclient=fromserver.readLine(); File clientfile=new File(filefromclient);
11311111111;lklklk
13
FileOutputStream fout=new FileOutputStream(clientfile); int ch; while ((ch=fromserver.read())!=-1) { fout.write((char)ch); } fout.close(); } if (option.equalsIgnoreCase("download")) { System.out.println("download test"); String filefromclient=fromserver.readLine(); File clientfile=new File(filefromclient); FileInputStream fis=new FileInputStream(clientfile); PrintStream out=new PrintStream(sl.getOutputStream()); int n=fis.read(); while (n!=-1) { out.print((char)n); n=fis.read(); } fis.close(); out.close(); } //while } }catch (Exception e) { System.out.println(e); // TODO: handle exception } } } FTPClient.java import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; class One extends JFrame implements ActionListener { /* ctrl space */ public JButton b,b1; public JLabel l; public JLabel l1,lmsg1,lmsg2;
11411111111;lklklk
14 One() { b=new JButton("Upload"); l=new JLabel("Uplaod a file : "); lmsg1=new JLabel(""); b1=new JButton("Download"); l1=new JLabel("Downlaod a file"); lmsg2=new JLabel(""); setLayout(new GridLayout(2,3,10,10)); add(l);add(b);add(lmsg1);add(l1);add(b1);add(lmsg2); b.addActionListener(this); b1.addActionListener(this); setVisible(true); setSize(600,500); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { /* String s=e.getActionCommand(); if(s.equals("Upload"))*/ if (b.getModel().isArmed()) { Socket s=new Socket("localhost",1010); System.out.println("Client connected to server"); JFileChooser j=new JFileChooser(); int val; val=j.showOpenDialog(One.this); String filename=j.getSelectedFile().getName(); String path=j.getSelectedFile().getPath(); PrintStream out=new PrintStream(s.getOutputStream()); out.println("Upload"); out.println(filename); FileInputStream fis=new FileInputStream(path); int n=fis.read(); while (n!=-1) { out.print((char)n);n=fis.read(); } fis.close(); out.close();lmsg1.setText(filename+"is uploaded"); //s.close(); repaint();
11511111111;lklklk
15 } if (b1.getModel().isArmed()) { Socket s=new Socket("localhost",1010); System.out.println("Client connected to server"); String remoteadd=s.getRemoteSocketAddress().toString(); System.out.println(remoteadd); JFileChooser j1=new JFileChooser(remoteadd); int val; val=j1.showOpenDialog(One.this); String filename=j1.getSelectedFile().getName(); String filepath=j1.getSelectedFile().getPath(); System.out.println("File name:"+filename); PrintStream out=new PrintStream(s.getOutputStream()); out.println("Download"); out.println(filepath); FileOutputStream fout=new FileOutputStream(filename); DataInputStream fromserver=new DataInputStream(s.getInputStream()); int ch; while ((ch=fromserver.read())!=-1) { fout.write((char) ch); } fout.close();//s.close(); lmsg2.setText(filename+"is downlaoded"); repaint(); } } catch (Exception ee) { // TODO: handle exception System.out.println(ee); } } } public class FTPClient { public static void main(String[] args) { new One(); } }
11611111111;lklklk
16 Output:
Upload Service: File will be selected from local drive and store in server directory Download Service: File will be selected from remote machine and stored in client directory
11711111111;lklklk
17
DESCRIPTION: Multi threaded chat server can support multiple clients by creating a new thread to process the requests from various client.
SOURCE CODE: CCLogin.java import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel;import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.GridLayout; public class CCLogin implements ActionListener { JFrame frame1; JTextField tf,tf1; JButton button; JLabel heading; JLabel label,label1; public static void main(String[] paramArrayOfString) { new CCLogin(); } public CCLogin() { this.frame1 = new JFrame("Login Page"); this.tf = new JTextField(10); this.button = new JButton("Login"); this.heading = new JLabel("Chat Server"); this.heading.setFont(new Font("Impact", 1, 40)); this.label = new JLabel("Enter you Login Name"); this.label.setFont(new Font("Serif", 0, 24)); JPanel localJPanel = new JPanel();
11811111111;lklklk
18 this.button.addActionListener(this); localJPanel.add(this.heading); localJPanel.add(this.label); localJPanel.add(this.tf); localJPanel.add(this.button); this.heading.setBounds(30, 20, 280, 50); this.label.setBounds(20, 100, 250, 60); this.tf.setBounds(50, 150, 150, 30); this.button.setBounds(70, 190, 90, 30); this.frame1.add(localJPanel); localJPanel.setLayout(null); this.frame1.setSize(300,300); this.frame1.setVisible(true); this.frame1.setDefaultCloseOperation(3); } public void actionPerformed(ActionEvent paramActionEvent) { String str = ""; try { str = this.tf.getText(); this.frame1.dispose(); Client1 c1= new Client1(str); c1.main(null); } catch(Exception localIOException) { } } } ChatMultiServer.java import java.net.*; import java.io.*; class A implements Runnable { Thread t; Socket s; A(Socket x) { s=x; t=new Thread(this); t.start(); } public void run() { try
11911111111;lklklk
19 { /* Reading data from client */ InputStream is=s.getInputStream(); byte data[]=new byte[50]; is.read(data); String mfc=new String(data); mfc=mfc.trim(); System.out.println(mfc); /* Sending message to the server */ //System.out.println("Hi"+name+"u can start chating"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String n=br.readLine(); OutputStream os=s.getOutputStream(); os.write(n.getBytes()); } catch(Exception e) { e.printStackTrace(); } }} class ChatMultiServer {static int c=0; public static void main(String args[]) throws Exception { System.out.println("ServerSocket is creating"); ServerSocket ss=new ServerSocket(1010); System.out.println("ServerSocket is created"); System.out.println("waiting for the client from the client"); while(true){Socket s=ss.accept();new A(s); } }} Client1.java import java.net.*; import java.io.*; class Client1 { static String name=""; public Client1(String n) { name=n; } public static void main(String args[]) throws Exception { System.out.println("connecting to server"); System.out.println("client1 connected to server"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); /* Sending message to the server */ System.out.println("Hi\t"+name+" u can start chating"); while(true){Socket s=new Socket("localhost",1010); String n=br.readLine();OutputStream os=s.getOutputStream(); os.write(n.getBytes()); /* Reading data from client */ InputStream is=s.getInputStream(); byte data[]=new byte[50]; is.read(data); String mfc=new String(data); mfc=mfc.trim(); System.out.println(mfc); } } }
12011111111;lklklk
20 Output:
12 11 11 11 11 1;l klk lk
21
12211111111;lklklk
22
DESCRIPTION: In group communication various peers will join the group to send and receive messages. Class D IP addresses are used for group communication.
SOURCE CODE: MulticastPeer.java import java.net.*; import java.io.*; public class MulticastPeer{ public static void main(String args[]){ // args give message contents and destination multicast group (e.g. "228.5.6.7") MulticastSocket s =null; try { InetAddress group = InetAddress.getByName(args[1]); s = new MulticastSocket(6789); s.joinGroup(group); byte [] m = args[0].getBytes(); DatagramPacket messageOut = new DatagramPacket(m, m.length, group, 6789); s.send(messageOut); byte[] buffer = new byte[1000]; for(int i=0; i< 3;i++) {// get messages from others in group DatagramPacket messageIn = new DatagramPacket(buffer, buffer.length); s.receive(messageIn); System.out.println("Received:" + new String(messageIn.getData()));} s.leaveGroup(group); }catch (SocketException e){System.out.println("Socket: " + e.getMessage()); }catch (IOException e){System.out.println("IO: " + e.getMessage()); }finally {if(s != null) s.close();} } }
12311111111;lklklk
23 Output:
12411111111;lklklk
24
DESCRIPTION: Domain Name System (DNS) - A hierarchical, distributed database that contains mappings of DNS domain names to various types of data, such as IP addresses. DNS enables the specification of computers and services by user-friendly names, and it also enables the discovery of other information stored in the database.
URL http://www.cdk3.net:8888/WebExamples/earth.html DNS lookup Resource ID (IP number, port number, pathname) 55.55.55.55 8888 WebExamples/earth.html
12511111111;lklklk
Main
IP number Domain name for server Domain name for alias Parameters governing the zone List of service names and protocols Domain name Machine architecture and operating system List of < preference, host > pairs Arbitrary text
12611111111;lklklk
26
9. Providing GUI Support for DNS operations addhost, lookup,Remove and Refresh.
AIM: Provide GUI Support for DNS operations addhost, lookup,Remove and Refresh HARDWARE REQUIREMENTS: Pentium 4 Processor, 256 MB RAM, 40GB HDD SOFTWARE REQUIREMENTS: JDK 1.5,JRE 1.5, J2SE 5.0 API and Redhat Server
DESCRIPTION: Create DNS Client to support addhost, lookup,Remove and Refresh operations and also handle events by using event handlers. SOURCE CODE: import java.awt.event.*; import javax.swing.*; import java.awt.*;import java.io.*; import java.net.*; class dnsclientGUI extends JFrame implements ActionListener{ JButton b1,b2,b3,b4;JPanel p1,p2;JLabel l1,l2;JTextField t1,t2; dnsclientGUI() { b1=new JButton("addhost");b2=new JButton("lookup"); b3=new JButton("Remove");b4=new JButton("Exit");p1=new JPanel(); p2=new JPanel(); l1=new JLabel("Host");l2=new JLabel("IP"); t1=new JTextField("",20);t2=new JTextField("",20); p1.setLayout(new FlowLayout());p1.add(l1);p1.add(t1); p1.add(l2);p1.add(t2);p2.add(b1);p2.add(b2);p2.add(b3);p2.add(b4); add(p1,"North");add(p2,"South");setSize(300,300); setVisible(true); b1.addActionListener(this);b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); } public void actionPerformed(ActionEvent e) { String s=e.getActionCommand();try { if(s.equals("addhost")){System.out.println("addhost"); System.out.println(t1.getText());System.out.println(t2.getText()); } if(s.equals("lookup")) { System.out.println("lookup"); System.out.println(t1.getText()); }
12711111111;lklklk
27
if(s.equals("Remove")) { System.out.println("Remove"); System.out.println(t1.getText()); } if(s.equals("Exit")) System.exit(0); }catch(Exception e1){e1.printStackTrace();} } public static void main(String args[])throws Exception { dnsclientGUI g=new dnsclientGUI();}} Output: java dnsclientGUI
12811111111;lklklk
28
AIM: To implement a mini DNS protocol using RPC HARDWARE REQUIREMENTS: Pentium 4 Processor, 256 MB RAM, 40GB HDD SOFTWARE REQUIREMENTS: JDK 1.5,JRE 1.5, J2SE 5.0 API and Redhat Server
DESCRIPTION: Domain Name Server will maintain the recode of IP addresses for corresponding URL. Reslover will run DNS server to fetch IP address for the given URL.
SOURCE CODE: DNS Server: import java.util.*;import java.io.*;import java.net.*; import java.awt.*; class NewServer1 { ServerSocket Server;Socket connection; DataOutputStream output;DataInputStream input;String s; Properties Clients=new Properties();FileInputStream fin=null; FileOutputStream fout=null;
NewServer1(){ try {fin=new FileInputStream("NameList2.txt"); if(fin!=null){Clients.load(fin); fin.close(); } Server=new ServerSocket(8037);connection=Server.accept(); output=new DataOutputStream(connection.getOutputStream()); input=new DataInputStream(connection.getInputStream());} catch(Exception e){ e.printStackTrace(); } }
12911111111;lklklk
29 try {s=input.readUTF(); if(s.equals("lookup")){ String s2=input.readUTF(); System.out.println(s2);String s1=lookup(s2); if(s1==null) output.writeUTF("host name not found"); else output.writeUTF("the ip address of"+s2+"is"+s1);}
if(s.equals("addhost")){ String s1=input.readUTF(); String s2=input.readUTF();boolean b=addhost(s1,s2); if(b==true)output.writeUTF("host name registered"); else output.writeUTF("host name alreadUTFy existing");}
if(s.equals("Remove")){ String s2=input.readUTF(); System.out.println(s2);String s1=(String)Clients.remove(s2); System.out.println(s1); if(s1==null) output.writeUTF("host name not found"); else output.writeUTF("the ip address is "+s1+" Removed"); fout=new FileOutputStream("NameList2.txt"); Clients.store(fout,"NameSpace");fout.close(); }
boolean addhost(String name,String ip){ if(Clients.get(name)!=null) return false; Clients.put(name,ip); try {fout =new FileOutputStream("NameList2.txt"); Clients.store(fout,"NameSpace");fout.close();} catch(IOException ex){ex.printStackTrace();}return true;}
13011111111;lklklk
30
DNS Client: import java.awt.event.*; import javax.swing.*; import java.awt.*;import java.io.*; import java.net.*; class newdnsclient extends JFrame implements ActionListener{ JButton b1,b2,b3,b4,b5;JPanel p1,p2;JLabel l1,l2;JTextField t1,t2; DataOutputStream output;DataInputStream input; newdnsclient() { /* Start of Socket Creation Code */ try { Socket s1=new Socket(InetAddress.getLocalHost(),8037); input=new DataInputStream(s1.getInputStream()); output=new DataOutputStream(s1.getOutputStream()); }catch(Exception e1){e1.printStackTrace();} /* End of Socket Creation Code */ b1=new JButton("addhost");b2=new JButton("lookup"); b3=new JButton("Remove");b4=new JButton("Refresh"); b5=new JButton("Close");p1=new JPanel(); p2=new JPanel(); l1=new JLabel("Host");l2=new JLabel("IP"); t1=new JTextField("",20);t2=new JTextField("",20); p1.setLayout(new FlowLayout());p1.add(l1);p1.add(t1); p1.add(l2);p1.add(t2);p2.add(b1);p2.add(b2);p2.add(b3);p2.add(b4); p2.add(b5); add(p1,"North");add(p2,"South");setSize(300,300); setVisible(true); b1.addActionListener(this);b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); } public void actionPerformed(ActionEvent e) { String s=e.getActionCommand(); try { if(s.equals("addhost")){output.writeUTF("addhost"); output.writeUTF(t1.getText());output.writeUTF(t2.getText()); s=input.readUTF();t2.setText(s);}
13111111111;lklklk
31
if(s.equals("lookup")) { output.writeUTF("lookup"); output.writeUTF(t1.getText());s=input.readUTF();t2.setText(s); } if(s.equals("Remove")) { output.writeUTF("Remove"); output.writeUTF(t1.getText());s=input.readUTF();t2.setText(s); } if(s.equals("Refresh")) {t1.setText("");t2.setText(""); } if(s.equals("Close")) {output.writeUTF("Close");System.exit(0);}
} catch(Exception e1) {} } public static void main(String args[])throws Exception { newdnsclient g=new newdnsclient();}} Output:
13 21 11 11 11 1;l klk lk
32
13311111111;lklklk
33
DESCRIPTION: Java Remote Method Invocation (RMI), which is a simple and powerful network object transport mechanism, provides a way for a Java program on one machine to communicate with objects residing in different address spaces. RMI is an implementation of the distributed object programming model, comparable with CORBA, but simpler, and specialized to the Java language. An overview of the RMI architecture is shown in Figure below:
13 41 11 11 11 1;l klk lk
34
13511111111;lklklk
35
DESCRIPTION: Java Remote Method Invocation (RMI), which is a simple and powerful network object transport mechanism, provides a way for a Java program on one machine to communicate with objects residing in different address spaces. SOURCE CODE: Hello.java:
public interface Hello extends java.rmi.Remote { String sayHello(String s) throws java.rmi.RemoteException; } HelloImpl.java: public class HelloImpl implements Hello { private int i; public HelloImpl() {} public String sayHello(String s) { i++; return "Hello " +s+ " yours is " +i+ " request"; } }
13611111111;lklklk
36
HelloClient.java: import java.rmi.*; class HelloClient { public static void main(String[] args) throws Exception { Remote ref = Naming.lookup("hello"); Hello h = (Hello)ref; String result = h.sayHello(args[0]); System.out.println(result); } }
HelloServer.java import java.rmi.*; import java.rmi.server.*; class HelloServer { public static void main(String[] args) throws Exception { HelloImpl remoteObj = new HelloImpl(); System.out.println("HelloImpl Created"); UnicastRemoteObject.exportObject(remoteObj); System.out.println("HelloImpl Exported"); Naming.rebind("hello", remoteObj); System.out.println("HelloImpl Binded"); } }
13711111111;lklklk
37
Output:
13811111111;lklklk
38
DESCRIPTION: Java Remote Method Invocation (RMI), which is a simple and powerful network object transport mechanism, provides a way for a Java program on one machine to communicate with objects residing in different address spaces. SOURCE CODE: ArithmeticIntf.java import java.rmi.*; interface ArithmeticIntf extends Remote { public double add(double a,double a1) throws RemoteException; public double sub(double b,double b1) throws RemoteException; public double mul(double c,double c1) throws RemoteException; public double div(double d,double d1) throws RemoteException; } ArithmeticImpl.java import java.rmi.*; import java.rmi.server.*; public class ArithmeticImpl extends UnicastRemoteObject implements ArithmeticIntf { public ArithmeticImpl() throws RemoteException {} public double add(double a,double a1) throws RemoteException { double res = a + a1; return res; }
13911111111;lklklk
39 public double sub(double b,double b1) throws RemoteException { double res = b - b1; return res; } public double mul(double c,double c1) throws RemoteException { double res = c * c1; return res; } public double div(double d,double d1) throws RemoteException { double res = d / d1; return res; }} ArithmeticServer.java //This program written to specify a name to the server so that the client can access it import java.rmi.*; import java.rmi.registry.*; import java.rmi.server.*; public class ArithmeticServer { public static void main(String args[]) throws Exception { ArithmeticImpl ob1 = new ArithmeticImpl(); java.rmi.registry.LocateRegistry.createRegistry(1099); /* rebind is a method in the Naming class which accepts two parameters. One is the remote interface name created by you. Second one is the object of the Server class in which all the methods has been implemented. This parameter is accepted to provide a name to the server so that the client can recognize it. * / Naming.rebind("rmiintf",ob1); } }
14011111111;lklklk
40
ArithmeticClient.java import java.rmi.*; class ArithmeticClient { public static void main(String args[]) throws Exception { /* we are designing an URL within which we can keep three options. 1. rmi service 2. ip address of the system in which your rmiserver is existing. 3. remote interface name */ String url = "rmi://"+args[0]+"/rmiintf"; /*lookup is a method which accepts the url created in order to search the rmi server and returns a reference which will be type casted as of remote interface type created by you and keep the reference within a reference variable of rmiintf. With the help of this reference we have to call the methods present within the rmi server. * / ArithmeticIntf ri = (ArithmeticIntf)Naming.lookup(url); double d = Double.parseDouble(args[1]); double d1 = Double.parseDouble(args[2]); double res = ri.add(d,d1); double res1 = ri.sub(d,d1); double res2 = ri.mul(d,d1); double res3 = ri.div(d,d1); System.out.println("Addition is : "+res); System.out.println("Subtraction is : "+res1); System.out.println("Multiplication is : "+res2); System.out.println("Division is : "+res3); } }
14111111111;lklklk
41
Output:
14211111111;lklklk
42
DESCRIPTION: Operations for two-phase commit protocol canCommit?(trans)-> Yes / No Call from coordinator to participant to ask whether it can commit a transaction. Participant replies with its vote. doCommit(trans) Call from coordinator to participant to tell participant to commit its part of a transaction. doAbort(trans) Call from coordinator to participant to tell participant to abort its part of a transaction. haveCommitted(trans, participant) Call from participant to coordinator to confirm that it has committed the transaction. getDecision(trans) -> Yes / No Call from participant to coordinator to ask for the decision on a transaction after it has voted Yes but has still had no reply after some delay. Used to recover from server crash or delayed messages.
The two-phase commit protocol Phase 1 (voting phase): 1. The coordinator sends a canCommit? request to each of the participants in
the transaction.
14311111111;lklklk
(Yes or No) to the coordinator. Before voting Yes, it prepares to commit by saving objects in permanent storage. If the vote is No the participant aborts immediately.
Phase 2 (completion according to outcome of vote): 3. (a) The coordinator collects the votes (including its own). If there are no failures and all the votes are Yes the coordinator decides to
commit the transaction and sends a doCommit request to each of the participants. (b) Otherwise the coordinator decides to abort the transaction and sends
doAbort requests to all participants that voted Yes. 4. Participants that voted Yes are waiting for a doCommit or doAbort request from the coordinator. When a participant receives one of these messages it acts accordingly and in the case of commit, makes a haveCommitted call as confirmation to the coordinator.
Coordinato ste 1 statu prepared to (waiting for 3 committe don canCommit Ye doCommi haveCommitte
14411111111;lklklk
44
T
Y T T T2
Client
import java.awt.event.ActionEvent;import java.awt.event.ActionListener; import java.io.IOException;import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel;//import javax.swing.JPanel; import javax.swing.JTextField;
14511111111;lklklk
45 import java.rmi.*; public class DistributedTransaction implements ActionListener { JFrame frame1;int ans; JTextField tf,tf1; JButton button,button1,button2; JLabel l1,l2,l3; public DistributedTransaction () { frame1 = new JFrame("home page"); button = new JButton("with draw"); button1 = new JButton("deposit"); button2 = new JButton("bal"); tf=new JTextField(20); tf1=new JTextField(10); l1=new JLabel("acc no "); l2=new JLabel("ammount "); l3=new JLabel( ""); frame1.setLayout(new FlowLayout()); frame1.setSize(300,300); frame1.setVisible(true); frame1.setDefaultCloseOperation(3); frame1.add(l1); frame1.add(l2); frame1.add(tf); frame1.add(tf1);
button.addActionListener(this); button2.addActionListener(this);
14611111111;lklklk
int acc=Integer.parseInt(tf.getText()); int amt=Integer.parseInt(tf1.getText()); System.out.println("after with drawn is " ); hr.withdraw( acc, amt); } if(button1.getModel().isArmed()) { HelloRemote hr1=(HelloRemote)Naming.lookup("r2"); int acc=Integer.parseInt(tf.getText()); int amt=Integer.parseInt(tf1.getText()); System.out.println("after deposit "); hr1.deposit(acc,amt); }
if(button2.getModel().isArmed()) { HelloRemote hr2=(HelloRemote)Naming.lookup("r1"); int acc=Integer.parseInt(tf.getText()); System.out.println("result balance"); ans=hr2.enquire(acc); System.out.println("is :"+ans); } } catch(Exception Ex) { } } public static void main(String args[])throws Exception { new DistributedTransaction();}}
14711111111;lklklk
47
Output:
// Internet banking System class IBS1 { public static void main (String [] args) { Account ao=new Account(); Thread t1=new Thread (new Mythread (ao)); Thread t2=new Thread (new Yourthread(ao)); Thread t3=new Thread (new Herthread(ao)); t1.start(); t2.start(); t3.start(); } } class Mythread implements Runnable { Account acc; public Mythread (Account s) { acc=s;} public void run() { synchronized(acc) { deposit(); }} } class Yourthread implements Runnable { Account acc; public Yourthread(Account s) { acc=s;} public void run() { synchronized (acc) { acc.withDraw(); }
14811111111;lklklk
48 } } class Herthread implements Runnable { Account acc; public Herthread (Account s) { acc=s;} public void run() { synchronized (acc) { acc.enquire(); } } }
class Account { int bal=5000,dept_amt=99, wt_amt=100; public void deposit() { bal+=dept_amt; } public void withDraw() { bal-=wt_amt; } public void enquire() { System.out.println ("bal is" + bal); } } Output:
14911111111;lklklk
49
DESCRIPTION:
Phase 1 (voting phase): 1. The coordinator sends a canCommit? request to each of the participants in
the transaction. 2. When a participant receives a canCommit? request it replies with its vote
(Yes or No) to the coordinator. Before voting Yes, it prepares to commit by saving objects in permanent storage. If the vote is No the participant aborts immediately.
Phase 2 (completion according to outcome of vote): 3. (a) The coordinator collects the votes (including its own). If there are no failures and all the votes are Yes the coordinator decides to
commit the transaction and sends a doCommit request to each of the participants. (b) Otherwise the coordinator decides to abort the transaction and sends
doAbort requests to all participants that voted Yes. 4. Participants that voted Yes are waiting for a doCommit or doAbort request from the coordinator. When a participant receives one of these messages it acts accordingly and in the case of commit, makes a haveCommitted call as confirmation to the coordinator.
15011111111;lklklk
50
SOURCE CODE: HelloRemote.java import java.rmi.*; public interface HelloRemote extends Remote { public void deposit(int acc,int amt)throws RemoteException; public void withdraw(int acc1,int amt2)throws RemoteException; public int enquire(int acc2)throws RemoteException; } HelloImpl.java import java.rmi.*; import java.rmi.server.*; import java.sql.*; public class HelloImpl extends UnicastRemoteObject implements HelloRemote { public HelloImpl()throws RemoteException { super(); } int bal=500,dep_amt=99,wd_amt=100; public void deposit(int acc,int amt) { int a; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:raviteja"); con.setAutoCommit(false) ; Statement st=con.createStatement(); a=st.executeUpdate("update ACCOUNT set BAl=BAL+'"+amt+"' where ACCNO='"+acc+"' "); con.commit(); } catch(Exception E) {} }
15111111111;lklklk
51
public void withdraw(int acc,int amt) { int a; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:raviteja"); con.setAutoCommit(false) ; Statement st=con.createStatement(); a=st.executeUpdate("update ACCOUNT set BAl=BAL-'"+amt+"' where ACCNO='"+acc+"' "); con.commit(); } catch(Exception E) {} } public int enquire(int acc) { int b=0; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:raviteja"); con.setAutoCommit(false) ; Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select BAl from ACCOUNT where ACCNO='"+acc+"' "); while (rs.next()) { b=rs.getInt("BAL"); } } catch(Exception E) {} return b; }}
15211111111;lklklk
52 HelloServer1.java import java.rmi.*; public class HelloServer1 { public static void main(String args[])throws Exception { HelloImpl hi=new HelloImpl(); Naming.rebind("r1",hi); } } HelloServer2.java import java.rmi.*; public class HelloServer2 { public static void main(String args[])throws Exception HelloImpl hi=new HelloImpl(); Naming.rebind("r2",hi); } } HelloServer.java import java.rmi.*; public class HelloServer { public static void main(String args[])throws Exception { HelloImpl hi=new HelloImpl(); Naming.rebind("robj",hi); } }
15311111111;lklklk
53 HelloClient.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; //import javax.swing.JPanel; import javax.swing.JTextField; import java.rmi.*; public class HelloClient implements ActionListener { JFrame frame1;int ans; JTextField tf,tf1; JButton button,button1,button2; JLabel l1,l2,l3; public HelloClient() { frame1 = new JFrame("home page"); button = new JButton("with draw"); button1 = new JButton("deposit"); button2 = new JButton("bal"); tf=new JTextField(20); tf1=new JTextField(10); l1=new JLabel("acc no "); l2=new JLabel("ammount "); l3=new JLabel( ""); frame1.setLayout(new FlowLayout()); frame1.setSize(300,300); frame1.setVisible(true); frame1.setDefaultCloseOperation(3); frame1.add(l1); frame1.add(tf); frame1.add(l2); frame1.add(tf1); frame1.add(button); frame1.add(button1); frame1.add(button2); frame1.add(l3); button.addActionListener(this); button1.addActionListener(this); button2.addActionListener(this); }
15411111111;lklklk
54
public void actionPerformed(ActionEvent es) { try { if(button.getModel().isArmed()) { HelloRemote hr=(HelloRemote)Naming.lookup("robj"); int acc=Integer.parseInt(tf.getText()); int amt=Integer.parseInt(tf1.getText()); System.out.println("after with drawn is " ); hr.withdraw( acc, amt); } if(button1.getModel().isArmed()) { HelloRemote hr1=(HelloRemote)Naming.lookup("r2"); int acc=Integer.parseInt(tf.getText()); int amt=Integer.parseInt(tf1.getText()); System.out.println("after deposit "); hr1.deposit(acc,amt); } if(button2.getModel().isArmed()) { HelloRemote hr2=(HelloRemote)Naming.lookup("r1"); int acc=Integer.parseInt(tf.getText()); System.out.println("result balance"); ans=hr2.enquire(acc); System.out.println("is :"+ans); } } catch(Exception Ex) { }} public static void main(String args[])throws Exception { new HelloClient();}}
15511111111;lklklk
55
Output:
15611111111;lklklk
56
17.Study of NFS
AIM: To Study Network File System HARDWARE REQUIREMENTS: Pentium 4 Processor, 256 MB RAM, 40GB HDD SOFTWARE REQUIREMENTS: Red hot Linux server and client
DESCRIPTION:
File system modules: Directory module: File module: Access control module: File access module: Block module: Device module: relates file names to file IDs relates file IDs to particular files checks permission for operation requested reads or writes file data or attributes accesses and allocates disk blocks disk I/O and buffering
15711111111;lklklk
lookup(dirfh, name) -> fh, attr create(dirfh, name, attr) -> newfh, attr remove(dirfh, name) status getattr(fh) -> attr setattr(fh, attr) -> attr read(fh, offset, count) -> attr, data write(fh, offset, count, data) -> attr rename(dirfh, name, todirfh, toname) -> status link(newdirfh, newname, dirfh, name) -> status
Returns file handle and attributes for the file name in the directory dirfh. Creates a new file name in directory dirfh with attributes attr and returns the new file handle and Removes file name from directory Returns file attributes of file fh. (Similar to the UNIX stat system call.) Sets the attributes (mode, user id, group id, size, access time and modify time of a file). Setting the size to 0 truncates the Returns up to count bytes of data from a file starting at offset. Also returns the latest attributes of the Writes count bytes of data to a file starting at offset. Returns the attributes of the file after the write has taken place. Changes the name of file name in directory dirfh to toname in directory to todi.rfh Creates an entry newname in the directory newdirfh which refers to file name in the directory Creates an entry newname in the directory newdirfh of symbolic link with the value string. The server does not the string but makes a symbolic link file to hold Returns the string that is associated with the symbolic link identified by Creates a new directory name with attributes attr and returns new file handle and Removes the empty directory name from the parent directory Fails if the directory is not Returns up to count bytes of directory entries from the dirfh. Each entry contains a file name, a file handle, and an pointer to the next directory entry, called a cookie. The cookie used in subsequent readdir calls to start reading from the entry. If the value of cookie is 0, reads from the first entry in directory Returns file system information (such as block size, number free blocks and so on) for the file system containing a file
symlink(newdirfh, newname, -> status readlink(fh) -> mkdir(dirfh, name, attr) > rmdir(dirfh, name) -> readdir(dirfh, cookie, count) >
statfs(fh) ->