Anda di halaman 1dari 51

Date: Roll no.

: 0208-8110

1. Program to implement File Transfer Protocol

//FTPServer.java

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

public class FTPServer


{
public static void main(String args[]) throws Exception
{
ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
{
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
}
}
}

class transferfile extends Thread


{
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;

transferfile(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
start();
}
catch(Exception ex)
{ }
}

void SendFile() throws Exception


{
String filename=din.readUTF();
1 Distributed Systems Lab
Date: Roll no. : 0208-8110

File f=new File(filename);


if(!f.exists())
{
dout.writeUTF("File Not Found");
return;
}
else
{
dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
dout.writeUTF("File Receive Successfully");
}
}

void ReceiveFile() throws Exception


{
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
{
return;
}
File f=new File(filename);
String option;
if(f.exists())
{
dout.writeUTF("File Already Exists");
option=din.readUTF();
}
else
{
dout.writeUTF("SendFile");
option="Y";
}
if(option.compareTo("Y")==0)
{
FileOutputStream fout=new FileOutputStream(f);
int ch;
2 Distributed Systems Lab
Date: Roll no. : 0208-8110

String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
dout.writeUTF("File Send Successfully");
}
else
{
return;
}
}

public void run()


{
while(true)
{
try
{
System.out.println("Waiting for Command ...");
String Command=din.readUTF();
if(Command.compareTo("GET")==0)
{
System.out.println("\tGET Command Received ...");
SendFile();
continue;
}
else if(Command.compareTo("SEND")==0)
{
System.out.println("\tSEND Command Receiced ...");
ReceiveFile();
continue;
}
else if(Command.compareTo("DISCONNECT")==0)
{
System.out.println("\tDisconnect Command Received ...");
System.exit(1);
}
}
3 Distributed Systems Lab
Date: Roll no. : 0208-8110

catch(Exception ex)
{ }
}
}
}

//FTPClient.java

import java.net.*;
import java.io.*;
4 Distributed Systems Lab
Date: Roll no. : 0208-8110

import java.util.*;

class FTPClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket("127.0.0.1",5217);
transferfileClient t=new transferfileClient(soc);
t.displayMenu();
}
}

class transferfileClient
{
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
BufferedReader br;

transferfileClient(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception ex)
{ }
}

void SendFile() throws Exception


{
String filename;
System.out.print("Enter File Name :");
filename=br.readLine();
File f=new File(filename);
if(!f.exists())
{
System.out.println("File not Exists...");
dout.writeUTF("File not found");
return;
}
dout.writeUTF(filename);
5 Distributed Systems Lab
Date: Roll no. : 0208-8110

String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Already Exists")==0)
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="Y")
{
dout.writeUTF("Y");
}
else
{
dout.writeUTF("N");
return;
}
}
System.out.println("Sending File ...");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
System.out.println(din.readUTF());
}

void ReceiveFile() throws Exception


{
String fileName;
System.out.print("Enter File Name :");
fileName=br.readLine();
dout.writeUTF(fileName);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Not Found")==0)
{
System.out.println("File not found on Server ...");
return;
}
else if(msgFromServer.compareTo("READY")==0)
{
System.out.println("Receiving File ...");
File f=new File(fileName);
6 Distributed Systems Lab
Date: Roll no. : 0208-8110

if(f.exists())
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="N")
{
dout.flush();
return;
}
}
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
System.out.println(din.readUTF());
}
}

public void displayMenu() throws Exception


{
while(true)
{
System.out.println("[ MENU ]");
System.out.println("1. Send File");
System.out.println("2. Receive File");
System.out.println("3. Exit");
System.out.print("\nEnter Choice :");
int choice;
choice=Integer.parseInt(br.readLine());
if(choice==1)
{
dout.writeUTF("SEND");
SendFile();
}
else if(choice==2)
7 Distributed Systems Lab
Date: Roll no. : 0208-8110

{
dout.writeUTF("GET");
ReceiveFile();
}
else
{
dout.writeUTF("DISCONNECT");
System.exit(1);
}
}
}
}

Output:
Server Client
>java FTPServer >java FTPClient
FTP Server Started on Port Number 5217 [ MENU ]
Waiting for Connection ... 1. Send File
FTP Client Connected ... 2. Receive File
Waiting for Connection ... 3. Exit
Waiting for Command ...
SEND Command Receiced ... Enter Choice :1
Waiting for Command ... Enter File Name :FTPClient.java
Disconnect Command Received ... File Already Exists. Want to OverWrite (Y/N) ?
Y
[ MENU ]
1. Send File
2. Receive File
3. Exit

Enter Choice :3

2. Program to implement File Transfer Protocol by providing a GUI for the access of all services

//FtpServer.java

import java.io.*;
import java.net.*;

public class FtpServer

8 Distributed Systems Lab


Date: Roll no. : 0208-8110

{
public static void main(String [] args)
{
int i=1;
System.out.println("***************");
System.out.println("**********");
System.out.println("********");
System.out.println("Server Started...");
System.out.println("Waiting for connections...");
System.out.println(" ");
try
{
ServerSocket s = new ServerSocket(100);
for(;;)
{
Socket incoming = s.accept();
System.out.println("New Client Connected with id " + i +" from "+
incoming.getInetAddress().getHostName()+"..." );
Thread t = new ThreadedServer(incoming,i);
i++;
t.start();
}
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}

class ThreadedServer extends Thread


{
int n;
String c,fn,fc;
String filenm;
Socket incoming;
int counter;
String dirn="c:/server";

public ThreadedServer(Socket i,int c)


{
incoming=i;
counter=c;
}

9 Distributed Systems Lab


Date: Roll no. : 0208-8110

public void run()


{
try
{
BufferedReader in =new BufferedReader(new
InputStreamReader(incoming.getInputStream()));
PrintWriter out = new
PrintWriter(incoming.getOutputStream(), true);
OutputStream output=incoming.getOutputStream();
fn=in.readLine();
c=fn.substring(0,1);
if(c.equals("#"))
{
n=fn.lastIndexOf("#");
filenm=fn.substring(1,n);
FileInputStream fis=null;
boolean filexists=true;
System.out.println("Request to download file " + filenm + " received
from " +incoming.getInetAddress().getHostName()+ "..." );
try
{
fis=new FileInputStream(filenm);
}
catch(FileNotFoundException exc)
{
filexists=false;
System.out.println("FileNotFoundException: "
+exc.getMessage());
}
if(filexists)
{
sendBytes(fis, output) ;
fis.close();
}
}
else
{
try
{
boolean done=true;
System.out.println("Request to upload file " +fn+ " received from "
+incoming.getInetAddress().getHostName()+ "...");
File dir=new File(dirn);
if(!dir.exists())
{
10 Distributed Systems Lab
Date: Roll no. : 0208-8110

dir.mkdir();
}
else
{ }
File f=new File(dir,fn);
FileOutputStream fos=new FileOutputStream(f);
DataOutputStream dops=new DataOutputStream(fos);
while(done)
{
fc=in.readLine();
if(fc==null)
{
done=false;
}
else
{
dops.writeChars(fc);
// System.out.println(fc);

}
}
fos.close();
}
catch(Exception ecc)
{
System.out.println(ecc.getMessage());
}
}
incoming.close();
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}

private static void sendBytes(FileInputStream f,OutputStream op) throws Exception


{
byte[] buffer=new byte[1024];
int bytes=0;
while((bytes=f.read(buffer))!=-1)
{
op.write(buffer,0,bytes);
}
}
11 Distributed Systems Lab
Date: Roll no. : 0208-8110

//FtpClient.java

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;

class FtpClient extends JFrame implements ActionListener


{
String fn,filenm;
12 Distributed Systems Lab
Date: Roll no. : 0208-8110

String fc;
String dirn="c:/client";
JPanel pnl;
JLabel lbltle,lblud;
Font fnt;
JTextField txtfn;
JButton btnu,btnd;
Socket s;
InputStreamReader in;
OutputStream out;
BufferedReader br;
PrintWriter pw;

public FtpClient()
{
super("FTP CLIENT");
pnl=new JPanel(null);
fnt=new Font("Times New Roman",Font.BOLD,25);
lbltle=new JLabel("FTP CLIENT");
lbltle.setFont(fnt);
lbltle.setBounds(225,35,200,30);
pnl.add(lbltle);
lblud=new JLabel("ENTER FILE-NAME :");
lblud.setBounds(100,100,150,35);
pnl.add(lblud);
txtfn=new JTextField();
txtfn.setBounds(300,100,200,25);
pnl.add(txtfn);
btnu=new JButton("UPLOAD");
btnu.setBounds(150,200,120,35);
pnl.add(btnu);
btnd=new JButton("DOWNLOAD");
btnd.setBounds(320,200,120,35);
pnl.add(btnd);
btnu.addActionListener(this);
btnd.addActionListener(this);
getContentPane().add(pnl);
try
{
s=new Socket("localhost",100);
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
pw=new PrintWriter(s.getOutputStream(),true);
out=s.getOutputStream();
}
catch(Exception e)
13 Distributed Systems Lab
Date: Roll no. : 0208-8110

{
System.out.println("ExCEPTION :"+e.getMessage());
}
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==btnu)
{
try
{
filenm=txtfn.getText();
pw.println(filenm);
FileInputStream fis=new FileInputStream(filenm);
byte[] buffer=new byte[1024];
int bytes=0;
while((bytes=fis.read(buffer))!=-1)
{
out.write(buffer,0,bytes);
}
fis.close();
}
catch(Exception exx)
{
System.out.println(exx.getMessage());
}
}
if(e.getSource()==btnd)
{
try
{
File dir=new File(dirn);
if(!dir.exists())
{
dir.mkdir();
}
else { }
boolean done=true;
filenm=txtfn.getText();
fn=new String("#"+filenm+"#");
//System.out.println(filenm);
pw.println(fn);
File f=new File(dir,filenm);
FileOutputStream fos=new FileOutputStream(f);
DataOutputStream dops=new DataOutputStream(fos);
14 Distributed Systems Lab
Date: Roll no. : 0208-8110

while(done)
{
fc=br.readLine();
if(fc==null)
{
done=false;
}
else
{
dops.writeChars(fc);
//System.out.println(fc);

}
}
fos.close();
}
catch(Exception exx)
{ }
}
}

public static void main(String args[])


{
FtpClient ftpc=new FtpClient();
ftpc.setSize(600,300);
ftpc.show();
}
}

Output:

Server

>java FtpServer
***************
**********
********
Server Started...
Waiting for connections...

New Client Connected with id 1 from 127.0.0.1...


Request to upload file a.txt received from 127.0.0.1...

15 Distributed Systems Lab


Date: Roll no. : 0208-8110

Client

>java FtpClient

3. Program to implement Remote Method Invocation

RMI Interface File


// myApplication.java

import java.rmi.*;
import java.rmi.RemoteException;

public interface myApplication extends Remote


{
String myMethod() throws RemoteException;
}

RMI Server
// myApplicationServer.java

16 Distributed Systems Lab


Date: Roll no. : 0208-8110

import java.rmi.*;
import java.rmi.server.*;

public class myApplicationServer extends UnicastRemoteObject implements myApplication


{
public myApplicationServer() throws RemoteException
{
super();
}

public String myMethod()


{
return "i am here to serve.\n";
}

public static void main(String[] args)


{
String app="//127.0.0.1/myApplication";
try{
myApplicationServer server=new myApplicationServer();
Naming.rebind(app,server);
}
catch(Exception error)
{
System.err.println("myApplicationServerException:"+error.getMessage());
}
}
}
RMI Client
// myApplicationClient.java

import java.rmi.*;

public class myApplicationClient


{
public static void main(String args[])
{
try
{
String app="//127.0.0.1/myApplication";
myApplication mApp=(myApplication) Naming.lookup(app);
System.out.println(mApp.myMethod());
}
catch(Exception error)
{
17 Distributed Systems Lab
Date: Roll no. : 0208-8110

System.err.println("myApplicationClientException:"+error.getMessage());
}
}
}

Output:

Server Client
>javac *.java >java myApplicationClient
>start rmiregistry i am here to serve.
>rmic myApplicationServer
>java myApplicationServer

4. Program to implement DNS protocol

import java.net.*;
import java.io.*;

public class NameServer


{
public static void main (String[] args)
{
if (args.length > 0)
{ }
else
{
BufferedReader buffer = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter an IP Address or Computer Name");
System.out.println("Enter \"exit\".");
try
18 Distributed Systems Lab
Date: Roll no. : 0208-8110

{
while (true)
{
String host = buffer.readLine();
if (host.equalsIgnoreCase("exit"))
{
break;
}
System.out.println(lookup(host));
}
}
catch (IOException ex)
{
System.err.println(ex);
}
}
}
private static String lookup(String hostname)
{
InetAddress node;
try
{
node = InetAddress.getByName(hostname);
}
catch (UnknownHostException ex)
{
return "Cannot find host " + hostname;
}
if (isHostname(hostname))
{
System.out.print("Host Address you have requested is : ");
return node.getHostAddress();
}
else
{
System.out.print("Host Name you have requested is : ");
return node.getHostName();
}
}

private static boolean isHostname(String host)


{
// Is this an IPv6 address?
if (host.indexOf(':') != -1) return false;
char[] ca = host.toCharArray();
19 Distributed Systems Lab
Date: Roll no. : 0208-8110

for (int i = 0; i < ca.length; i++)


{
if (!Character.isDigit(ca[i]))
{
if (ca[i] != '.') return true;
}
}
return false;

}
}

Output:

>java NameServer
Enter an IP Address or Computer Name
Enter "exit".
www.cbit.ac.in
Host Address you have requested is : 202.65.147.165
exit

5. Program to implement Chat Service using TELNET

//ChatServer.java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer


{
public static final int DEFAULT_PORT = 9800;
public static void main(String[] args)
{
int port = DEFAULT_PORT;
ServerSocket serverSocket = null;
Socket socket = null;
try
{
if(args.length > 0)
port = Integer.parseInt(args[0]);
20 Distributed Systems Lab
Date: Roll no. : 0208-8110

} catch(NumberFormatException nfe)
{
System.err.println("Usage: java ChatServer [port]");
System.err.println("Where options include:");
System.err.println("\tport- the port on which to listen.");
System.exit(0);
}
try
{
serverSocket = new ServerSocket(port);
while(true)
{
socket = serverSocket.accept();
ChatHandler handler = new ChatHandler(socket);
handler.start();
}
} catch(IOException ioe)
{
ioe.printStackTrace();
} finally
{
try {
serverSocket.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}

21 Distributed Systems Lab


Date: Roll no. : 0208-8110

//ChatHandler.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Vector;

public class ChatHandler extends Thread


{
static Vector handlers = new Vector( 10 );
private Socket socket;
private BufferedReader in;
private PrintWriter out;

public ChatHandler(Socket socket) throws IOException


{
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
22 Distributed Systems Lab
Date: Roll no. : 0208-8110

public void run()


{
String line;
String z;
synchronized(handlers)
{
handlers.addElement(this);
// add() not found in Vector class
}
try
{
for(int m = 0;m < handlers.size(); m++)
{
ChatHandler handlerr = (ChatHandler)handlers.elementAt(m);
handlerr.out.println("B.E 4/4 C-2 CHAT ROOM");
handlerr.out.println("The number of users connected are : " +
handlers.size());
handlerr.out.flush();
}

while(!(line = in.readLine()).equalsIgnoreCase("/quit"))
{
for(int i = 0; i < handlers.size(); i++)
{
synchronized(handlers)
{
ChatHandler handler = (ChatHandler)handlers.elementAt(i);
handler.out.println( ":" +line + "\r");
handler.out.flush();
}
}
}
} catch(IOException ioe)
{
ioe.printStackTrace();
} finally
{
try
{
in.close();
out.close();
socket.close();
} catch(IOException ioe)
23 Distributed Systems Lab
Date: Roll no. : 0208-8110

{ }
finally
{
synchronized(handlers)
{
handlers.removeElement(this);
}
}
}
}
}

Output:

Server
>java ChatServer.java

Client

Client 1 Client 2
B.E 4/4 C-2 CHAT ROOM B.E 4/4 C-2 CHAT ROOM
The number of users connected are : 1 The number of users connected are : 2
B.E 4/4 C-2 CHAT ROOM :Hello
The number of users connected are : 2 Hi
Hello :Hi
:Hello
:Hi

24 Distributed Systems Lab


Date: Roll no. : 0208-8110

6. Program to implement Chat Service by providing a GUI

//ChatServer.java

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer


{
/** What I call myself in system messages */
protected final static String CHATMASTER_ID = "ChatMaster";
/** What goes between any handle and the message */
protected final static String SEP = ": ";
/** The Server Socket */
protected ServerSocket servSock;
/** The list of my current clients */
protected ArrayList clients;
/** Debugging state */
private boolean DEBUG = false;
protected static int PORTNUM = 7777;

/** Main just constructs a ChatServer, which should never return */


public static void main(String[] argv)
25 Distributed Systems Lab
Date: Roll no. : 0208-8110

{
System.out.println(" Chat Server 0.1 starting...");
ChatServer w = new ChatServer( );
w.runServer( ); // should never return.
System.out.println("**ERROR* Chat Server 0.1 quitting");
}
/** Construct (and run!) a Chat Service */
ChatServer( )
{
clients = new ArrayList( );
try
{
servSock = new ServerSocket(PORTNUM);
System.out.println("Chat Server Listening on port " + PORTNUM);
}catch(IOException e)
{
log("IO Exception in ChatServer.<init>");
System.exit(0);
}
}

public void runServer( )


{
try
{
while (true)
{
Socket us = servSock.accept( );
String hostName = us.getInetAddress().getHostName( );
System.out.println("Accepted from " + hostName);
ChatHandler cl = new ChatHandler(us, hostName);
synchronized (clients)
{
clients.add(cl);
cl.start( );
if (clients.size( ) == 1)
cl.send(CHATMASTER_ID,"many clients are waiting");
else
{
cl.send(CHATMASTER_ID, "Welcome! you're the
latest of " + clients.size( ) + " users.");
}
}
}
}
26 Distributed Systems Lab
Date: Roll no. : 0208-8110

catch(IOException e)
{
log("IO Exception in runServer: " + e);
System.exit(0);
}
}

protected void log(String s)


{
System.out.println(s);
}

/** Inner class to handle one conversation */


protected class ChatHandler extends Thread
{
/** The client socket */
protected Socket clientSock;
/** BufferedReader for reading from socket */
protected BufferedReader is;
/** PrintWriter for sending lines on socket */
protected PrintWriter pw;
/** The client's host */
protected String clientIP;
/** String handle */
protected String login;

/* Construct a Chat Handler */


public ChatHandler(Socket sock, String clnt) throws IOException
{
clientSock = sock;
clientIP = clnt;
is = new BufferedReader( new InputStreamReader(sock.getInputStream( )));
pw = new PrintWriter(sock.getOutputStream( ), true);
pw.println("hi this is server");
}

/** Each ChatHandler is a Thread, so here's the run( ) method,


* which handles this conversation.
*/
public void run( )
{
String line;
try
{
while ((line = is.readLine( )) != null)
27 Distributed Systems Lab
Date: Roll no. : 0208-8110

{
char c = line.charAt(0);
line = line.substring(1);
switch (c)
{
case 'l': //login
login = line;
broadcast(CHATMASTER_ID, login +" joins
us, for a total of " + clients.size( ) + " users");
break;
case 'm': //to display message
if (login == null)
{
send(CHATMASTER_ID, "please
login first");
continue;
}
int where = line.indexOf(':');
if(where>1)
{
String recip =
line.substring(0, where);
String mesg =
line.substring(where+1);
log("MESG: " + login + "-->" + recip +
": "+mesg);
ChatHandler cl = lookup(recip);
if (cl == null)
psend(CHATMASTER_ID,
recip + " not loggedin.");
else
cl.psend(login, mesg);
}
else
{
String mesg = line;
broadcast(login,mesg);
}
break;
case 'q': //quit the server
broadcast(CHATMASTER_ID, "Goodbye to
"+login);
close( );
return; // END OF THIS CHATHANDLER
default: log("Unknown cmd " + c + " from " +
28 Distributed Systems Lab
Date: Roll no. : 0208-8110

login + "@"+ clientIP);


}
}
}
catch (IOException e)
{
log("IO Exception: " + e);
}
finally
{
// the sock ended, so we're done, bye now
// Can NOT send a good-bye message, until we have
// a simple command-based protocol in place.
System.out.println(login + SEP + "All Done");
synchronized(clients)
{
clients.remove(this);
if (clients.size( ) == 0)
{
System.out.println(CHATMASTER_ID + SEP +"Im so
lonely I could cry...");
}
else if (clients.size( ) == 1)
{
ChatHandler last = (ChatHandler)clients.get(0);
last.send(CHATMASTER_ID,"Hey, you're talking to
yourself again");
}
else
{
broadcast(CHATMASTER_ID,"There are now " +
clients.size( ) + " users");
}
}
}
}
protected void close( )
{
if (clientSock == null)
{
log("close when not open");
return;
}
try
{
29 Distributed Systems Lab
Date: Roll no. : 0208-8110

clientSock.close( );
clientSock = null;
}catch(IOException e)
{
log("Failure during close to " + clientIP);
}
}

/** Send one message to this user */


public void send(String sender, String mesg)
{
pw.println(sender + SEP + mesg);
}

/** Send a private message */


protected void psend(String sender, String msg)
{
send("<*" + sender + "*>", msg);
}

/** Send one message to all users */


public void broadcast(String sender, String mesg)
{
System.out.println("Broadcasting " + sender + SEP + mesg);
for (int i=0; i<clients.size( ); i++)
{
ChatHandler sib = (ChatHandler)clients.get(i);
if (DEBUG)
System.out.println("Sending to " + sib);
sib.send(sender, mesg+"\n");
}
if (DEBUG)
System.out.println("Done broadcast");
}

protected ChatHandler lookup(String nick)


{
synchronized(clients)
{
for (int i=0; i<clients.size( ); i++)
{
ChatHandler cl = (ChatHandler)clients.get(i);
if (cl.login.equals(nick))
return cl;
}
30 Distributed Systems Lab
Date: Roll no. : 0208-8110

}
return null;
}

/** Present this ChatHandler as a String */


public String toString( )
{
return "ChatHandler[" + login + "]";
}
}
}

//ChatRoom.java

import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatRoom extends JFrame implements ActionListener /*, Runnable*/


{
public static String ip;
boolean loggedIn=false;
boolean verif=false;
protected static int PORTNUM = 7777;
/** The actual port number */
public int port;
/** The network socket */
protected Socket sock;
/** BufferedReader for reading from socket */
public BufferedReader is;
public PrintWriter pw;
/** TextField for input */
public JTextField tf;
/** TextArea to display conversations */
public TextArea ta,warna;
final static String TITLE = "Chat: Chat Room ";
JButton lib,lob,send;
JPanel localpanel;
JFrame cp;
dispclass d;

31 Distributed Systems Lab


Date: Roll no. : 0208-8110

String name;

ChatRoom()
{
cp = new JFrame(TITLE);
cp.setLayout(new BorderLayout( ));
port = PORTNUM;
ta = new TextArea("",20, 80,0);
ta.setEditable(false); // readonly
ta.setFont(new Font("Monospaced", Font.PLAIN, 11));
cp.add(BorderLayout.NORTH, ta);
Panel p = new Panel( );
Button b;
// The login button
p.add(lib = new JButton("Login"));
lib.setEnabled(true);
lib.requestFocus( );
lib.addActionListener(this);
// The logout button
p.add(lob = new JButton("Logout"));
lob.setEnabled(false);
lob.addActionListener(this);
p.add(new Label("Message here:"));
tf = new JTextField(40);
tf.addActionListener(this);
p.add(tf);
p.add(send = new JButton("Send"));
send.setEnabled(false);
send.addActionListener(this);
//warna = new TextArea("",2, 80,0);
// warna.setEditable(false); // readonly
// warna.setFont(new Font("Monospaced", Font.PLAIN, 11));
// cp.add(BorderLayout.CENTRE,warna);
// //p.add(warna);
cp.add(BorderLayout.SOUTH, p);
cp.pack( );
// After packing the Frame, centre it on the screen.
Dimension us = cp.getSize( ),them = Toolkit.getDefaultToolkit().getScreenSize( );
int newX = (them.width - us.width) / 2;
int newY = (them.height- us.height)/ 2;
cp.setLocation(newX, newY);
cp.setVisible(true);
send.setEnabled(false);
d= new dispclass();
//c=new cheksend();
32 Distributed Systems Lab
Date: Roll no. : 0208-8110

cp.addWindowListener(new WindowAdapter( )
{
public void windowClosing(WindowEvent e)
{
// If we do setVisible and dispose, then the Close completes
ChatRoom.this.cp.setVisible(false);
ChatRoom.this.cp.dispose( );
d.t.stop();
logout( );
}
});
}

class dispclass implements Runnable


{
public Thread t;
public dispclass()
{
t=new Thread(this,"disp");
t.start();
}
public void run( )
{
String line;
try
{
ta.append("4/4 CSE C-2 Chat Room"+ "\n");
while(true)
{
if(loggedIn)
{
line = is.readLine( );
if (!(line.equals("")))
ta.append(line + "\n");
}
}
}
catch(Exception e)
{
ta.append("some exception in thread of disp class"+e+"\n");
//t.start();
}
}
}
33 Distributed Systems Lab
Date: Roll no. : 0208-8110

/** LOG ME IN TO THE CHAT */


public void login1()
{
ta.append("Enter your Name:");
verif = true;
send.setEnabled(true);
}

public void login( )


{
loggedIn = true;
lib.setEnabled(false);
lob.setEnabled(true);
tf.requestFocus( );

// construct and start the reader: from server to textarea


// make a Thread to avoid lockups.
// FAKE LOGIN FOR NOW
}

/** Log me out, Scotty, there's no intelligent life here! */


public void logout( )
{
if (!loggedIn) return;
loggedIn = false;
try
{
if (sock != null)
{
pw.println("q");
sock.close( );
}
send.setEnabled(false);
}
catch (IOException ign)
{
// so what?
}
}

public void actionPerformed(ActionEvent ae)


{
try
34 Distributed Systems Lab
Date: Roll no. : 0208-8110

{
String s=ae.getActionCommand();
if("Login".equals(s))
{
login1( );
if(loggedIn)
{
lib.setEnabled(false);
lob.setEnabled(true);
tf.requestFocus( ); // set keyboard focus in rightplace!
}
//send.setEnabled(true);
}
if("Logout".equals(s))
{
logout( );
lib.setEnabled(true);
lob.setEnabled(false);
//send.setEnabled(false);
lib.requestFocus( );
}
if("Send".equals(s))
{
String line;
if(tf.getText().length()!=0 )
if(loggedIn )
{
pw.println("m"+tf.getText());
tf.setText("");
}
else
{
name=tf.getText();
try
{
//System.out.println(InetAddress.getLocalHost());
sock = new Socket(ip,port);
is = new BufferedReader(new
InputStreamReader(sock.getInputStream( )));
pw = new PrintWriter(sock.getOutputStream( ),
true);
loggedIn = true;
}
catch(IOException e)
{
35 Distributed Systems Lab
Date: Roll no. : 0208-8110

ta.append("Can't get socket: "+ e+"\n");


loggedIn = false;
return;
}
pw.println("l"+name);
ta.append(tf.getText() + "\n");
tf.setText("");
login();
}
tf.requestFocus( ); // set keyboard focus in rightplace!
}
}
catch(Exception e)
{
System.out.println(e);
}
}

public static void main(String args[]) throws Exception


{
try
{
if(args[0].length()<0)
{
System.out.println("IP addr should be included in command lin");
return;
}
else
{
ChatRoom d1=new ChatRoom();
ip=args[0];
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("way of execution\nexample:-\njava <filename> <ip
address of server>");
}
}
}

36 Distributed Systems Lab


Date: Roll no. : 0208-8110

Output:

Server
>java ChatServer
Chat Server 0.1 starting...
Chat Server Listening on port 7777
Accepted from 127.0.0.1
Broadcasting ChatMaster: Rahul joins us, for a total of 1 users
Broadcasting Rahul: Hello C2
Broadcasting ChatMaster: Goodbye to Rahul
Rahul: All Done
ChatMaster: Im so lonely I could cry...

Client
>java ChatRoom 127.0.0.1

37 Distributed Systems Lab


Date: Roll no. : 0208-8110

7. Program to implement Two-phase Commit protocol for distributed transaction management

import java.sql.*;
import javax.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.*;
import oracle.jdbc.pool.OracleDataSource;
import oracle.jdbc.xa.OracleXid;
import oracle.jdbc.xa.OracleXAException;
import oracle.jdbc.xa.client.*;
import javax.transaction.xa.*;

class TwoPC
{
public static void main (String args []) throws SQLException
{
try
{
String URL1 = "jdbc:oracle:thin:@172.16.2.56:1521:master";
String URL2 = "jdbc:oracle:thin:@172.16.2.56:1521:slave";

DriverManager.registerDriver(new OracleDriver());

// You can put a database name after the @ sign in the connection URL
Connection conna =DriverManager.getConnection (URL1, "system", "cbit");

// Prepare a statement to create the table


Statement stmta = conna.createStatement ();
Connection connb = DriverManager.getConnection (URL2, "system", "cbit");

// Prepare a statement to create the table


Statement stmtb = connb.createStatement ();
try
{
// Drop the test table
stmta.execute ("drop table my_table");
}
catch (SQLException e)
{
// Ignore an error here
38 Distributed Systems Lab
Date: Roll no. : 0208-8110

}
try
{
// Create a test table
stmta.execute ("create table my_table (col1 int)");
}
catch (SQLException e)
{
// Ignore an error here too
}
try
{
// Drop the test table
stmtb.execute ("drop table my_tab");
}
catch (SQLException e)
{
// Ignore an error here
}
try
{
// Create a test table
stmtb.execute ("create table my_tab (col1 char(30))");
}
catch (SQLException e)
{
// Ignore an error here too
}
// Create a XADataSource instance
OracleXADataSource oxds1 = new OracleXADataSource();
oxds1.setURL("jdbc:oracle:thin:@172.16.2.56:1521:master");
oxds1.setUser("system");
oxds1.setPassword("cbit");
OracleXADataSource oxds2 = new OracleXADataSource();
oxds2.setURL("jdbc:oracle:thin:@172.16.2.56:1521:slave");
oxds2.setUser("system");
oxds2.setPassword("cbit");

// Get a XA connection to the underlying data source


XAConnection pc1 = oxds1.getXAConnection();

// We can use the same data source


XAConnection pc2 = oxds2.getXAConnection();

// Get the Physical Connections


39 Distributed Systems Lab
Date: Roll no. : 0208-8110

Connection conn1 = pc1.getConnection();


Connection conn2 = pc2.getConnection();

// Get the XA Resources


XAResource oxar1 = pc1.getXAResource();
XAResource oxar2 = pc2.getXAResource();

// Create the Xids With the Same Global Ids


Xid xid1 = createXid(1);
Xid xid2 = createXid(2);

// Start the Resources


oxar1.start (xid1, XAResource.TMNOFLAGS);
oxar2.start (xid2, XAResource.TMNOFLAGS);

// Do something with conn1 and conn2


doSomeWork1 (conn1);
doSomeWork2 (conn2);

// END both the branches -- THIS IS MUST


oxar1.end(xid1, XAResource.TMSUCCESS);
oxar2.end(xid2, XAResource.TMSUCCESS);

// Prepare the RMs


int prp1 = oxar1.prepare (xid1);
int prp2 = oxar2.prepare (xid2);
System.out.println("Return value of prepare1 is " + prp1);
System.out.println("Return value of prepare2 is " + prp2);
boolean do_commit = true;
if (!((prp1 == XAResource.XA_OK) || (prp1 == XAResource.XA_RDONLY)))
do_commit = false;
if (!((prp2 == XAResource.XA_OK) || (prp2 == XAResource.XA_RDONLY)))
do_commit = false;
System.out.println("do_commit is " + do_commit);
System.out.println("Is oxar1 same as oxar2 ? " + oxar1.isSameRM(oxar2));
if (prp1 == XAResource.XA_OK)
if (do_commit)
oxar1.commit (xid1, false);
else
oxar1.rollback (xid1);
if (prp2 == XAResource.XA_OK)
if (do_commit)
oxar2.commit (xid2, false);
else
oxar2.rollback (xid2);
40 Distributed Systems Lab
Date: Roll no. : 0208-8110

// Close connections
conn1.close();
conn1 = null;
conn2.close();
conn2 = null;
pc1.close();
pc1 = null;
pc2.close();
pc2 = null;
ResultSet rset = stmta.executeQuery ("select col1 from my_table");
while (rset.next())
System.out.println("Col1 is " + rset.getInt(1));
rset.close();
rset = null;
rset = stmtb.executeQuery ("select col1 from my_tab");
while (rset.next())
System.out.println("Col1 is " + rset.getString(1));
rset.close();
rset = null;
stmta.close();
stmta = null;
stmtb.close();
stmtb = null;
conna.close();
conna = null;
connb.close();
connb = null;
} catch (SQLException sqe)
{
sqe.printStackTrace();
} catch (XAException xae)
{
if (xae instanceof OracleXAException)
{
System.out.println("XA Error is " +
((OracleXAException)xae).getXAError());
System.out.println("SQL Error is " +
((OracleXAException)xae).getOracleError());
}
}
}

static Xid createXid(int bids) throws XAException


41 Distributed Systems Lab
Date: Roll no. : 0208-8110

{
byte[] gid = new byte[1]; gid[0]= (byte) 9;
byte[] bid = new byte[1]; bid[0]= (byte) bids;
byte[] gtrid = new byte[64];
byte[] bqual = new byte[64];
System.arraycopy (gid, 0, gtrid, 0, 1);
System.arraycopy (bid, 0, bqual, 0, 1);
Xid xid = new OracleXid(0x1234, gtrid, bqual);
return xid;
}

private static void doSomeWork1 (Connection conn) throws SQLException


{
// Create a Statement
Statement stmt = conn.createStatement ();
int cnt = stmt.executeUpdate ("insert into my_table values (4321)");
System.out.println("No. of Rows affected: " + cnt);
stmt.close();
stmt = null;
}

private static void doSomeWork2 (Connection conn) throws SQLException


{
// Create a Statement
Statement stmt = conn.createStatement ();
int cnt = stmt.executeUpdate ("insert into my_tab values ('test')");
System.out.println("No. of Rows affected: " + cnt);
stmt.close();
stmt = null;
}
}

Output:

>java TwoPC
No. of Rows affected: 1
No. of Rows affected: 1
Return value of prepare1 is 0
Return value of prepare2 is 0
do_commit is true
Is oxar1 same as oxar2 ? false
Col1 is 4321
Col1 is test

42 Distributed Systems Lab


Date: Roll no. : 0208-8110

8. Network File System (NFS) Case Study

The network file system (NFS), designed by Sun Microsystems, Inc. in the 1980s, is a client/service
application that provides shared file storage for clients across a network. An NFS client grafts a
remote file system onto the client’s local file system name space and makes it behave like a local
UNIX file system. Multiple clients can mount the same remote file system so that users can share
files.

In the early 1980s, it became economically feasible to build workstations, which allowed each
engineer to have a private computer. But, users desired to still have a shared file system for ease of
collaboration. NFS provides exactly that: it allows a user at any workstation to use files stored on a
shared server, a powerful workstation with local disks but often without a graphical display.

NFS also simplifies the management of a collection of workstations. Without NFS, a system
administrator must manage each workstation and, for example, arrange for backups of each
workstation’s local disk. NFS allows for centralized management; for example, a system
administrator needs to back up only the disks of the server to archive the file system. In the 1980s,
the setup had also a cost benefit: NFS allowed organizations to buy workstations without disks,
saving the cost of a disk interface on every workstation and, at the time, the cost of unused disk
space on each workstation.

The design of NFS had four major goals:

 It should work with existing applications, which means NFS ideally should provide the same
semantics as a local UNIX file system.
 NFS should be deployable easily, which means its implementation should be able to retrofit
into existing UNIX systems.
 The client should be implementable in other operating systems such as Microsoft’s DOS, so
that a user on a personal computer can have access to the files on an NFS server; this goal
implies that the client design cannot be too UNIX-specific.
 Finally, NFS should be efficient enough to be tolerable to users, but it doesn’t have to
provide as high performance as local file systems. NFS only partially achieves these goals.

43 Distributed Systems Lab


Date: Roll no. : 0208-8110

NFS Architecture:

NFS Server Operations:

 read(fh, offset, count) -> attr, data


 write(fh, offset, count, data) -> attr
 create(dirfh, name, attr) -> newfh, attr
 remove(dirfh, name) status
 getattr(fh) -> attr
 setattr(fh, attr) -> attr
 lookup(dirfh, name) -> fh, attr
 rename(dirfh, name, todirfh, toname)
 link(newdirfh, newname, dirfh, name)
 readdir(dirfh, cookie, count) -> entries
 symlink(newdirfh, newname, string) -> status
 readlink(fh) -> string
 mkdir(dirfh, name, attr) -> newfh, attr
 rmdir(dirfh, name) -> status
 statfs(fh) -> fsstats

Naming Remote files and directories:

44 Distributed Systems Lab


Date: Roll no. : 0208-8110

User programs can name remote files in the same way as local files. When a user program invokes,
say, OPEN (“/users/smith/.profile”, READONLY), it cannot tell from the path name whether “users”
or “smith” are local or remote directories.

To make naming remote file transparent to users and their programs, the client must mount the root
directory of a remote file system on the local name space. NFS performs this operation by using a
separate program, called the mounter. This program serves a similar function as the MOUNT call; it
grafts the remote file system— named by host:path, where host is a DNS name and path a path
name—onto the local file name space. The mounter sends a remote procedure call to the file server
host and asks for a file handle, a 32-byte name, for the inode of path. On receiving the reply, the
client marks the mount point in the local file system as a remote file system. It also remembers the
file handle for path and the network address for the server.

NFS doesn’t use path names to name files and directories internally, but instead uses file handles. To
the client a file handle is a 32-byte opaque name that identifies an inode on a remote server. A client
obtains file handles from the server when the client mounts a remote file system or it looks up a file
in a directory on the server. In all subsequent remote procedures calls to the server for that file, the
client includes the file handle.

File handles are usable names across server failures, so that even if the server computer fails
between a client program opening a file and then reading from the file, the server can identify the
file using the information in the file handle.

Interaction between a NFS Client and Server:

Suppose we have the following fragment of a user program:

fd = OPEN (“f”, READONLY);

45 Distributed Systems Lab


Date: Roll no. : 0208-8110

READ (fd, buf, n);

The above figure shows the corresponding timing diagram where ‘f’ is a remote file. The NFS client
implements each file system operation using one or remote procedure calls. In response to the
program’s call to OPEN, the NFS client sends the following remote procedure call to the server:

LOOKUP (dirfh, “f”);

From before the program runs, the client has a file handle for the current working directory's (dirfh).
It obtained this handle as a result of a previous lookup or as a result of mounting the remote file
system.

On receiving the LOOKUP request, the NFS server extracts the file system identifier from dirfh, and
asks the identified file system to look up the inode for dirfh. The identified file system uses the inode
number in dirfh to locate the directory’s inode. Now the NFS server searches the directory for the
inode for “f”. If present, the server creates a handle for the “f”. The handle contains the file system
identifier of the local file system, the inode number for “f”, and the generation number stored in f’s
inode. The NFS server sends this file handle to the client.

On receiving the response, the client allocates the first unused entry in the program’s file descriptor
table, stores a reference to f’s file handle in that entry, and returns the index for the entry (fd) to the
user program.

Next, the program calls READ (fd, buf, n). The client sends the following remote procedure call to the
NFS server:

READ (fh, 0, n);

Like with the directory file handle, the NFS server looks up the inode for fh. Then, the server reads
the data and sends the data in a reply message to the client. The NFS remote procedure calls are
designed so that the server can be stateless, that is the server doesn’t need to maintain any other
state than the on-disk files. NFS achieves this property by making each remote procedure call
contain all the information necessary to carry out that request. The server does not maintain any
state about past remote procedure calls to process a new request.

9. Distributed Databases- Database Partitioning

A partition is a division of a logical database or its constituting elements into distinct independent
parts. Database partitioning is normally done for manageability, performance or availability reasons.
46 Distributed Systems Lab
Date: Roll no. : 0208-8110

A popular and favourable application of partitioning is in a distributed database management


system. Each partition may be spread over multiple nodes, and users at the node can perform local
transactions on the partition. This increases performance for sites that have regular transactions
involving certain views of data, whilst maintaining availability and security.

The partitioning can be done by either building separate smaller databases (each with its own tables,
indices, and transaction logs), or by splitting selected elements, for example just one table.

Horizontal partitioning (also see shard) involves putting different rows into different tables. Perhaps
customers with ZIP codes less than 50000 are stored in CustomersEast, while customers with ZIP
codes greater than or equal to 50000 are stored in CustomersWest. The two partition tables are
then CustomersEast and CustomersWest, while a view with a union might be created over both of
them to provide a complete view of all customers.

Vertical partitioning involves creating tables with fewer columns and using additional tables to store
the remaining columns. Normalization also involves this splitting of columns across tables, but
vertical partitioning goes beyond that and partitions columns even when already normalized. Done
explicitly or implicitly, this type of partitioning is called "row splitting" (the row is split by its
columns). A common form of vertical partitioning is to split (slow to find) dynamic data from (fast to
find) static data in a table where the dynamic data is not used as often as the static. Creating a view
across the two newly created tables restores the original table with a performance penalty, however
performance will increase when accessing the static data e.g. for statistical analysis.

Partitioning criteria:

Current high end relational database management systems provide for different criteria to split the
database. They take a partitioning key and assign a partition based on certain criteria. Common
criteria are:
47 Distributed Systems Lab
Date: Roll no. : 0208-8110

1. Range partitioning

Selects a partition by determining if the partitioning key is inside a certain range. An example
could be a partition for all rows where the column zipcode has a value between 70000 and 79999.

Code:

SQL> create table students


2 (
3 rollno number(8),
4 name varchar(25),
5 dob date,
6 )
7 partition by range(rollno)
8 (
9 partition batch1 values less than (02088090),
10 partition batch2 values less than (02088115),
11 partition batch3 values less than (maxvalue),
12 );

Table created.

2. List partitioning

A partition is assigned a list of values. If the partitioning key has one of these values, the partition
is chosen. For example all rows where the column Country is either Iceland, Norway, Sweden,
Finland or Denmark could build a partition for the Nordic countries.

48 Distributed Systems Lab


Date: Roll no. : 0208-8110

Code:

SQL> create table students


SQL>
2 (create table students
2
3 ( rollno number(8),
3
4 rollno varchar(25),
name number(8),
4
5 ) name varchar(25),
5
6 partitionbatch number(1),
by hash(rollno)
6
7 ()
7
8 partitionpartition
by list(batch)
batch1,
8
9 ( partition batch2,
9
10 partition batch1
batch3,values(1),
10 );
11 partition batch2 values(2),
11 partition batch3 values(3),
12 created.
Table );

Table created.

3. Hash partitioning

The value of a hash function determines membership in a partition. Assuming there are four
partitions, the hash function could return a value from 0 to 3.

Code:

49 Distributed Systems Lab


Date: Roll no. : 0208-8110

Composite partitioning allows for certain combinations of the above partitioning schemes, for
example first applying a range partitioning and then a hash partitioning. Consistent hashing could be
considered a composite of hash and list partitioning where the hash reduces the key space to a size
that can be listed.

To view a partition:

10. Database Replication

Database replication is the creation and maintenance of multiple copies of the same database. In
most implementations of database replication, one database server maintains the master copy of
the database and additional database servers maintain slave copies of the database. Database writes
are sent to the master database server and are then replicated by the slave database servers.
Database reads are divided among all of the database servers, which results in a large performance
advantage due to load sharing. In addition, database replication can also improve availability
because the slave database servers can be configured to take over the master role if the master
database server becomes unavailable.

Database Replication in MYSQL:

Master Slave
Step 1: Step 1:
mysql> GRANT REPLICATION SLAVE mysql> CHANGE MASTER TO
-> ON *.* TO 'user_name'@'master_host' -> MASTER_HOST='master_host',
-> IDENTIFIED BY 'user_password'; -> MASTER_PORT=master_port,
-> MASTER_USER='slave_user',
-> MASTER_PASSWORD='slave_password';

SQL> select * from students partition batch1;Step 2:


You will need to edit the following my.ini file on
the slave.
server-id=2

Step 2: Step 3:
mysql> SHOW MASTER STATUS\G; mysql> CHANGE MASTER TO
Once you have obtain the Master Status, please -> MASTER_LOG_FILE='[file]',
note down the 2 most important info, which is -> MASTER_LOG_POS=[position];
50 Distributed Systems Lab
Date: Roll no. : 0208-8110

the "File" and "Position". You will need this info


to setup on the slave on the next part.
Step 4: Start the Slave service
mysql> Slave Start;

Step 3: Step 5:
To show master status, use the following To show slave status, use the following
command command
mysql> SHOW MASTER STATUS\G; mysql> SHOW SLAVE STATUS\G;
mysql> SHOW PROCESSLIST\G; mysql> SHOW PROCESSLIST\G;

51 Distributed Systems Lab

Anda mungkin juga menyukai