You are on page 1of 69

1. Program to demonstrate simple chat without threads using UDP input from keyboard. UDPClient.

java:
import java.io.*; import java.net.*; public class UDPClient { public static void main(String args[]) { DatagramSocket aSocket = null; try { aSocket = new DatagramSocket(); InetAddress aHost = InetAddress.getByName(args[0]); int serverPort = 6789; while(true) { System.out.println("Enter message to send"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); String temp = dataIn.readLine(); byte [] m = temp.getBytes(); DatagramPacket request = new DatagramPacket(m, temp.length(), aHost, serverPort); aSocket.send(request); byte[] buffer = new byte[1000]; DatagramPacket reply = new DatagramPacket(buffer, buffer.length); aSocket.receive(reply); System.out.println("Reply: " + new String(reply.getData())); } } catch (SocketException e)
Page | 1

{ System.out.println("Socket: " + e.getMessage()); } catch (IOException e) { System.out.println("IO: " + e.getMessage()); } finally { if(aSocket != null) aSocket.close(); } } }

Page | 2

UDPServer.java:
import java.net.*; import java.io.*; public class UDPServer { public static void main(String args[]) { DatagramSocket aSocket = null; try { aSocket = new DatagramSocket(6789); byte[] buffer = new byte[1000]; while(true) { DatagramPacket request = new DatagramPacket(buffer, buffer.length); aSocket.receive(request); System.out.println("Reply: " + new String(request.getData())); System.out.println("Enter message to send"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); String temp = dataIn.readLine(); byte [] m = temp.getBytes(); DatagramPacket reply = new DatagramPacket(m,temp.length(), request.getAddress(), request.getPort()); aSocket.send(reply); } } catch (SocketException e) { System.out.println("Socket: " + e.getMessage()); } catch (IOException e) { System.out.println("IO: " + e.getMessage()); }
Page | 3

} finally { if(aSocket != null) aSocket.close(); } } }

Output:

Page | 4

2. Program to demonstrate simple chat without threads using TCP input from keyboard. TCPClient.java:
import java.net.*; import java.io.*; public class TCPClient { public static void main (String args[]) { Socket s = null; try { int serverPort = 7896; s = new Socket(args[0], serverPort); DataInputStream in = new DataInputStream( s.getInputStream()); DataOutputStream out = new DataOutputStream( s.getOutputStream()); while(true) { System.out.println("Enter message to send"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); String temp = dataIn.readLine(); out.writeUTF(temp); String data = in.readUTF(); System.out.println("Received: "+ data) ; } } catch (UnknownHostException e) { System.out.println("Sock:"+e.getMessage()); } catch (EOFException e) {
Page | 5

System.out.println("EOF:"+e.getMessage()); } catch (IOException e) { System.out.println("IO:"+e.getMessage()); } finally { if(s!=null) try { s.close(); } catch (IOException e) { System.out.println("close:"+e.getMessage()); } } } }

Page | 6

TCPServer.java:
import java.net.*; import java.io.*; public class TCPServer { public static void main (String args[]) { try { int serverPort = 7896; ServerSocket listenSocket = new ServerSocket(serverPort); while(true) { Socket clientSocket = listenSocket.accept(); Connection c = new Connection(clientSocket); } } catch(IOException e) { System.out.println("Listen :"+e.getMessage()); } } } class Connection extends Thread { DataInputStream in; DataOutputStream out; Socket clientSocket; public Connection (Socket aClientSocket) { try { clientSocket = aClientSocket; in = new DataInputStream( clientSocket.getInputStream()); out =new DataOutputStream( clientSocket.getOutputStream()); this.start();
Page | 7

} catch(IOException e) { System.out.println("Connection:"+e.getMessage()); } } public void run() { try { while(true) { String data = in.readUTF(); System.out.println("Recieved: " + data); System.out.println("Enter message to send"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); String temp = dataIn.readLine(); out.writeUTF(temp); } } catch(EOFException e) { System.out.println("EOF:"+e.getMessage()); } catch(IOException e) { System.out.println("IO:"+e.getMessage()); } finally { try { clientSocket.close(); } catch (IOException e) { }
Page | 8

} } }

Output:

3. Program to demonstrate chat application with thread using UDP.


Page | 9

Client.java:
import java.net.*; import java.io.*; class NewThread implements Runnable { String name; Thread t; InputStream is; OutputStream os; DataOutputStream dos; DataInputStream din; BufferedReader dataIn; NewThread(String threadname,Socket s1) { try { name=threadname; t= new Thread(this,name); System.out.println("New Thread:"+t); dos=new DataOutputStream(s1.getOutputStream()); is=s1.getInputStream(); dataIn=new BufferedReader(new InputStreamReader(System.in)); din=new DataInputStream(is); t.start(); } catch(Exception e) { System.out.println("Exception: " + name +e); System.out.println("Stack trace" + e.getStackTrace()); } } public void run() { try {
Page | 10

if(name.equals("Client Send")) { while(true) { String st= dataIn.readLine(); dos.writeUTF(st); if(st.equals("end")) { t.sleep(1000); break; } } //while }//if if(name.equals("Client Receive")) { while(true) { String sl= din.readUTF(); if(sl.equals("end")) break; System.out.println("CLIENT RECIEVED:-- "+sl); }//while }//if }//try catch (Exception e) { System.out.println(name+" "); } System.out.println(name+" thread exiting."); }//run }//NewThread class Client { public static void main(String args[]) throws Exception { try {
Page | 11

Socket s= new Socket(InetAddress.getLocalHost(),5005); NewThread ob1= new NewThread("Client Send",s); NewThread ob2= new NewThread("Client Receive",s); System.out.println("waiting for the thread to finish---- NOW START CHATTING"); ob1.t.join(); ob2.t.join(); } catch(Exception e) { System.out.println("main thread interrupted" + e); } System.out.println("main thread exiting"); } }

Server.java:
Page | 12

import java.net.*; import java.io.*; class NewThread1 implements Runnable { String name; Thread t; OutputStream os; InputStream is; DataOutputStream dos; DataInputStream d; DataInputStream din; BufferedReader dataIn; NewThread1(String threadname,Socket s) { try { name=threadname; t= new Thread(this,name); System.out.println("New Thread1:"+t); if(name.equals("Server Recieve")) t.sleep(5000); dos=new DataOutputStream(s.getOutputStream()); is=s.getInputStream(); dataIn=new BufferedReader(new InputStreamReader(System.in)); din=new DataInputStream(is); t.start(); } catch(Exception e) { System.out.println("Exception"+ name + e.getStackTrace()); } } public void run() { try { if(name.equals("Server Send"))
Page | 13

{ while(true) { String st= dataIn.readLine(); dos.writeUTF(st); if(st.equals("end")) { t.sleep(1000); break; } } //while }//if if(name.equals("Server Receive")) { while(true) { String sl= din.readUTF(); if(sl.equals("end")) break; System.out.println("SERVER RECIEVED:-- "+sl); }//while }//if }//try catch (Exception e) { System.out.println(name+" "); } System.out.println(name+" thread exiting."); }//run }//NewThread1 class Server { public static void main(String args[]) throws Exception { try { ServerSocket ss=new ServerSocket(5005);; Socket s=ss.accept();
Page | 14

NewThread1 ob1= new NewThread1("Server Send",s); NewThread1 ob2= new NewThread1("Server Receive",s); System.out.println("waiting for the thread to finish-- NOW START CHATTING"); ob1.t.join(); ob2.t.join(); } catch(Exception e) { System.out.println("main thread interrupted"); } System.out.println("main thread exiting"); }}

Output:

4. Program to demonstrate chat application with thread using TCP. Client.java:


Page | 15

import java.net.*; import java.io.*; class NewThread implements Runnable { String name; Thread t; NewThread(String threadname) { try { name=threadname; t= new Thread(this,name); System.out.println("New Thread:"+t); t.start(); } catch(Exception e) { System.out.println("Exception: " + name +e); System.out.println("Stack trace" + e.getStackTrace()); } } public void run() { try { InetAddress aHost = InetAddress.getByName("localhost"); int serverPort = 7000; if(name.equals("Client Send")) { while(true) { System.out.println("Enter message to send"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); String temp = dataIn.readLine();
Page | 16

byte [] m = temp.getBytes(); DatagramPacket request = new DatagramPacket(m,temp.length(), aHost, serverPort); DatagramSocket aSocket=new DatagramSocket(); aSocket.send(request); if(temp.equals("end")) { t.sleep(1000); break; } } //while }//if if(name.equals("Client Receive")) { DatagramSocket bSocket=new DatagramSocket(7001); while(true) { byte[] buffer = new byte[1000]; DatagramPacket reply = new DatagramPacket(buffer, buffer.length); bSocket.receive(reply); String s1= new String(reply.getData()); if(s1.equals("end")) break; System.out.println("CLIENT RECIEVED:-- "+s1); }//while }//if }//try catch (Exception e) { System.out.println(name+" "); } System.out.println(name+" thread exiting."); }//run }//NewThread class Client { public static void main(String args[]) throws Exception
Page | 17

{ try { NewThread ob1= new NewThread("Client Send"); NewThread ob2= new NewThread("Client Receive"); System.out.println("waiting for the thread to finish---- NOW START CHATTING"); ob1.t.join(); ob2.t.join(); } catch(Exception e) { System.out.println("main thread interrupted" + e); } System.out.println("main thread exiting"); } }

Server.java:
import java.net.*;
Page | 18

import java.io.*; class NewThread1 implements Runnable { String name; Thread t; byte [] buffer; DatagramSocket aSocket; DatagramSocket bSocket; NewThread1(String threadname) { try{ name=threadname; t= new Thread(this,name); System.out.println("New Thread1:"+t); t.start(); } catch(Exception e) { System.out.println("Exception"+ name + e.getStackTrace()); } } public void run() { try { InetAddress aHost = InetAddress.getByName("localhost"); int serverPort = 7001; if(name.equals("Server Send")) { while(true) { System.out.println("Enter message to send"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); String temp = dataIn.readLine(); aSocket=new DatagramSocket(); byte [] m = temp.getBytes(); DatagramPacket reply = new DatagramPacket(m,temp.length(),aHost,serverPort);
Page | 19

aSocket.send(reply); if(temp.equals("end")) { t.sleep(1000); break; } } //while }//if if(name.equals("Server Receive")) { bSocket=new DatagramSocket(7000); while(true) { buffer = new byte[1000]; DatagramPacket request = new DatagramPacket(buffer, buffer.length); bSocket.receive(request); String s1=new String(request.getData()); if(s1.equals("end")) break; System.out.println("SERVER RECIEVED:-- "+s1); }//while }//if }//try catch (Exception e) { System.out.println(name+ e +" "); } System.out.println(name+" thread exiting."); }//run }//NewThread1 class Server { public static void main(String args[]) throws Exception{ try { NewThread1 ob1= new NewThread1("Server Send"); NewThread1 ob2= new NewThread1("Server Receive"); System.out.println("waiting for the thread to finish-- NOW START CHATTING"); ob1.t.join(); ob2.t.join(); }
Page | 20

catch(Exception e) { System.out.println("main thread interrupted"); } System.out.println("main thread exiting"); }}

Output:

5. Program to demonstrate chat application in GUI using UDP. ClientChat.java:


Page | 21

import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import java.util.*; public class ClientChat extends JFrame implements ActionListener { JButton send = new JButton("SEND"); JTextArea area = new JTextArea(20,20); JScrollPane jsp = new JScrollPane(area); JTextField text = new JTextField(20); JLabel label = new JLabel("Enter Ur Text :: "); JPanel panel = new JPanel(); DatagramSocket aSocket,bSocket; public DatagramPacket request,reply; InetAddress aHost; int serverPort; public ClientChat() { super("Client Window"); panel.add(label); panel.add(text); panel.add(send); panel.setBorder(new LineBorder(Color.red,2,true)); add(panel,BorderLayout.SOUTH); jsp.setBorder(new EmptyBorder(10,10,10,10)); add(jsp); send.addActionListener(this); text.addActionListener(this); area.setFont(new Font("TimesRoman",Font.PLAIN,15)); area.setEditable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(500,500); setLocationRelativeTo(null); setVisible(true);
Page | 22

try { aSocket=aSocket = new DatagramSocket(); bSocket = new DatagramSocket(6790); aHost = InetAddress.getByName("localhost"); serverPort = 6789; } catch(Exception e) { System.out.println("\n\tException " + e); } } public void receive() { try { String s; byte[] buffer = new byte[1000]; DatagramPacket reply = new DatagramPacket(buffer, buffer.length); while(true) { bSocket.receive(reply); s=new String(reply.getData()); String temp = "\nServer : " + s ; area.append(temp); } } catch(Exception e) { System.out.println("Exception " + e); } } public void actionPerformed(ActionEvent ae) { try { String s = "\nClient : " + text.getText() ;
Page | 23

area.append(s); byte [] m = text.getText().getBytes(); DatagramPacket request = new DatagramPacket(m, (text.getText()).length(), aHost, serverPort); aSocket.send(request); text.setText(""); } catch(Exception e) { System.out.println("Exception " + e); } } public static void main(String args[]) { new ClientChat().receive(); } }

ServerChat:
import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*;
Page | 24

import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import java.util.*; public class ServerChat extends JFrame implements ActionListener { JButton send = new JButton("SEND"); JTextArea area = new JTextArea(20,20); JScrollPane jsp = new JScrollPane(area); JTextField text = new JTextField(20); JLabel label = new JLabel("Enter Ur Text :: "); JPanel panel = new JPanel(); DatagramSocket aSocket,bSocket; InetAddress aHost; public static DatagramPacket request,reply; int serverPort1; public ServerChat() { super("Server Window"); panel.add(label); panel.add(text); panel.add(send); panel.setBorder(new LineBorder(Color.red,2,true)); add(panel,BorderLayout.SOUTH); jsp.setBorder(new EmptyBorder(10,10,10,10)); add(jsp); area.setFont(new Font("TimesRoman",Font.PLAIN,15)); area.setEditable(false); send.addActionListener(this); text.addActionListener(this); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(500,500); setLocationRelativeTo(null); setVisible(true); try { aSocket = new DatagramSocket(6789);
Page | 25

bSocket = new DatagramSocket(); aHost = InetAddress.getByName("localhost"); serverPort1 = 6790; area.setText("Server Is Waiting For Client"); } catch(Exception e) { System.out.println("\n\tException " + e); } } public void receive() { try { String s; byte[] buffer = new byte[1000]; request = new DatagramPacket(buffer, buffer.length); while(true) { aSocket.receive(request); s= new String(request.getData()); String temp = "\nClient : " + s ; s=null; area.append(temp); } } catch(Exception e) { System.out.println("Exception " + e); } } public void actionPerformed(ActionEvent ae) { try { String s1=text.getText(); String s = "\nServer : " + s1 ; area.append(s);
Page | 26

byte [] m = s1.getBytes(); reply = new DatagramPacket(m,s1.length(), aHost, serverPort1); bSocket.send(reply); text.setText(""); } catch(Exception e) { System.out.println("Exception " + e.getStackTrace()); } } public static void main(String args[]) { new ServerChat().receive(); } }

Output:

Page | 27

6. Program to demonstrate chat application in GUI using TCP.

Page | 28

ClientChat.java:
import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import java.util.*; public class ClientChat extends JFrame implements ActionListener { JButton send = new JButton("SEND"); JTextArea area = new JTextArea(20,20); JScrollPane jsp = new JScrollPane(area); JTextField text = new JTextField(20); JLabel label = new JLabel("Enter Ur Text :: "); JPanel panel = new JPanel(); Socket client; DataInputStream din; PrintWriter pw; public ClientChat() { super("Client Window"); panel.add(label); panel.add(text); panel.add(send); panel.setBorder(new LineBorder(Color.red,2,true)); add(panel,BorderLayout.SOUTH); jsp.setBorder(new EmptyBorder(10,10,10,10)); add(jsp); send.addActionListener(this); text.addActionListener(this); area.setFont(new Font("TimesRoman",Font.PLAIN,15)); area.setEditable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(500,500);
Page | 29

setLocationRelativeTo(null); setVisible(true); try { client = new Socket("localhost",2000); pw = new PrintWriter(client.getOutputStream()); din = new DataInputStream(client.getInputStream()); } catch(Exception e) { System.out.println("\n\tException " + e); } } public void receive() { try { String s; while((s=din.readLine())!=null) { String temp = "\nServer : " + s ; area.append(temp); } } catch(Exception e) { System.out.println("Exception " + e); } } public void actionPerformed(ActionEvent ae) { try { String s = "\nClient : " + text.getText() ; area.append(s); pw.println(text.getText()); pw.flush(); text.setText("");
Page | 30

} catch(Exception e) { System.out.println("Exception " + e); } } public static void main(String args[]) { new ClientChat().receive(); } }

ServerChat.java:
Page | 31

import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import java.util.*; public class ServerChat extends JFrame implements ActionListener { JButton send = new JButton("SEND"); JTextArea area = new JTextArea(20,20); JScrollPane jsp = new JScrollPane(area); JTextField text = new JTextField(20); JLabel label = new JLabel("Enter Ur Text :: "); JPanel panel = new JPanel(); ServerSocket server; Socket client; DataInputStream din; PrintWriter pw; public ServerChat() { super("Server Window"); panel.add(label); panel.add(text); panel.add(send); panel.setBorder(new LineBorder(Color.red,2,true)); add(panel,BorderLayout.SOUTH); jsp.setBorder(new EmptyBorder(10,10,10,10)); add(jsp); area.setFont(new Font("TimesRoman",Font.PLAIN,15)); area.setEditable(false); send.addActionListener(this); text.addActionListener(this); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(500,500);
Page | 32

setLocationRelativeTo(null); setVisible(true); try { server = new ServerSocket(2000); area.setText("Server Is Waiting For Client"); client = server.accept(); area.append("\nClient Is Now Connected"); pw = new PrintWriter(client.getOutputStream()); din = new DataInputStream(client.getInputStream()); } catch(Exception e) { System.out.println("\n\tException " + e); } } public void receive() { try { String s; while((s=din.readLine())!=null) { String temp = "\nClient : " + s ; area.append(temp); } } catch(Exception e) { System.out.println("Exception " + e); } } public void actionPerformed(ActionEvent ae) { try { String s = "\nServer : " + text.getText() ; area.append(s); pw.println(text.getText()); pw.flush();
Page | 33

text.setText(""); } catch(Exception e) { System.out.println("Exception " + e); } } public static void main(String args[]) { new ServerChat().receive(); }}

Output:

7. Program to demonstrate two phase commit protocol.


Page | 34

Coordinator.java:
import java.net.*; import java.io.*; class NewThread implements Runnable { String name; Thread t; Socket s; OutputStream os; InputStream is; PrintStream ps; DataInputStream in; Counter c; NewThread(String threadname,Counter c,int portnumber) { try { this.c=c; name=threadname; t= new Thread(this,name); s = new Socket(InetAddress.getLocalHost(),portnumber); os = s.getOutputStream(); is = s.getInputStream(); ps = new PrintStream(os); in = new DataInputStream(is); t.start(); }//try catch(Exception e) { System.out.println("Exception: "+name+e.getStackTrace()); } }//Constructor public void run() { try
Page | 35

{ ps.println("Can Commit?"); System.out.println("Asking the participant whether to commit."); String s1 = in.readLine(); if(s1.equals("Yes Commit")) { c.increment(); System.out.println(c.counter); while(c.counter<c.nump); if(c.allflag) { System.out.println("Recieved 'Yes Commit' from participant."); ps.println("Commit"); System.out.println("Asking participant to Commit."); s1=in.readLine(); if(s1.equals("ack")) { System.out.println("coordinator rcvs Acknolodgement"); System.out.println("Coordinator committed."); } } else { ps.println("Rollback"); System.out.println("Asking participant to Rollback."); s1=in.readLine(); if(s1.equals("ack")) { System.out.println("coordinator rcvs Acknolodgement"); System.out.println("Coordinator rolled back."); } } }
Page | 36

else if(s1.equals("Failure")) { c.allflag=false; System.out.println("Recieved 'Failure' from participant."); ps.println("Rollback"); c.increment(); System.out.println("Asking participant to Rollback."); s1=in.readLine(); if(s1.equals("ack")) { System.out.println("coordinator rcvs Acknolodgement"); System.out.println("Coordinator rolled back."); } } }//try catch(Exception e) { System.out.println("Exception"+ name + e.getStackTrace()); } }//run }//NewThread class Coordinator { public static void main(String args[]) throws Exception { int portnumber = 7000; Counter c = new Counter(); int numP = Integer.parseInt(args[0]); c.nump=numP; NewThread ob[]= new NewThread[5]; for(int i=0;i<numP;i++) { ob[i] = new NewThread("Participant",c,portnumber); portnumber++; } for(int i=0;i<numP;i++) {
Page | 37

ob[i].t.join(); } }//main }//class Coordinator class Counter { public static int counter; public static boolean allflag=true; public static int nump; synchronized int increment() { counter++; return 0; } }

Participant.java:
Page | 38

import java.net.*; import java.io.*; class Participant { public static void main(String args[]) throws Exception { int portnumber = Integer.parseInt(args[0]); ServerSocket ss = new ServerSocket(portnumber); Socket s = ss.accept(); OutputStream os = s.getOutputStream(); InputStream is = s.getInputStream(); PrintStream ps = new PrintStream (os); DataInputStream din = new DataInputStream(is); Thread t=new Thread(); String s1 = din.readLine(); if(s1.equals("Can Commit?")) { System.out.println("Recieved 'Can Commit?' from coordinator."); } double i = Math.random()*10; int flag = (int) i; System.out.println("Random number generated is " + flag); if(flag == 1 || flag == 2 || flag == 3) { ps.println("Failure"); System.out.println("Sent 'Failure' to coordinator."); } else { ps.println("Yes Commit"); System.out.println("Sent 'Yes Commit' to coordinator."); } String s2 = din.readLine(); if(s2.equals("Commit")) { System.out.println("Recieved 'Commit' from coordinator."); ps.println("ack"); System.out.println("Participant committed."); }
Page | 39

else if(s2.equals("Rollback")) { System.out.println("Recieved 'Rollback' from coordinator."); ps.println("ack"); System.out.println("Participant Rolled back."); } s.close(); }}

Output:

8. Program to demonstrate RMI.


Page | 40

AddClient.java:
import java.rmi.*; public class AddClient { public static void main(String args[]) { try { String addServerURL="rmi://"+args[0]+"/AddServer"; AddServerIntf addServerIntf= (AddServerIntf)Naming.lookup(addServerURL); System.out.println("First no. is"+args[1]); double d1=Double.valueOf(args[1]).doubleValue(); System.out.println("Second no. is"+args[2]); double d2=Double.valueOf(args[2]).doubleValue(); System.out.println("the sum is "+addServerIntf.add(d1,d2)); } catch(Exception e) { System.out.println("Exception:" +e); } } }

AddServer.java:
import java.rmi.*; import java.rmi.server.*; public class AddServer { public static void main(String args[]) { try { AddServerImpl addServerImpl=new AddServerImpl();
Page | 41

Naming.rebind("AddServer",addServerImpl); } catch(Exception e) { System.out.println("Exception:" +e); } } }

AddServerImpl.java:
import java.rmi.*; import java.rmi.server.*; public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf { public AddServerImpl() throws RemoteException { } public double add(double d1,double d2) throws RemoteException { return d1+d2; } }

AddServerIntf.java:
import java.rmi.*; public interface AddServerIntf extends Remote { double add(double d1,double d2) throws RemoteException; }

Output:
Page | 42

Page | 43

9. Program to create Name Server using RMI keeping data in the program itself. DNSClient.java:
import java.rmi.*; public class DNSClient { public static void main(String args[]) { try { String dnsServerURL="rmi://"+args[0]+"/DNSServer"; DNSServerIntf dnsServerIntf= (DNSServerIntf)Naming.lookup(dnsServerURL); System.out.println("The website name is "+args[1]); String s1=args[1]; System.out.println("the sum is "+dnsServerIntf.DNS(s1)); } catch(Exception e) { System.out.println("Exception:" +e); } } }

DNSServer.java:
import java.rmi.*; import java.rmi.server.*; public class DNSServer { public static void main(String args[]) { try { DNSServerImpl dnsServerImpl=new DNSServerImpl();
Page | 44

Naming.rebind("DNSServer",dnsServerImpl); } catch(Exception e) { System.out.println("Exception:" +e); } } }

DNSServerImpl.java:
import java.rmi.*; import java.rmi.server.*; public class DNSServerImpl extends UnicastRemoteObject implements DNSServerIntf { public DNSServerImpl() throws RemoteException { } public String DNS(String s1) throws RemoteException { if(s1.equals("www.osmania.ac.in")) return "50.32.24.29"; if(s1.equals("www.mjcollege.ac.in")) return "90.82.44.89"; if(s1.equals("www.jntu.ac.in")) return "150.32.64.20"; if(s1.equals("www.yahoo.com")) return "88.39.124.129"; else return "No Info about this address"; } }

DNSServerIntf.java:
import java.rmi.*;
Page | 45

public interface DNSServerIntf extends Remote { String DNS(String s1) throws RemoteException; }

Output:

Page | 46

10. Program to create Name Server using RMI retrieving data from file. DNSClient.java:
import java.rmi.*; public class DNSClient { public static void main(String args[]) { try{ String dnsServerURL="rmi://"+args[0]+"/DNSServer"; DNSServerIntf dnsServerIntf=(DNSServerIntf)Naming.lookup(dnsServerURL); System.out.println("the ip address of "+args[1]); System.out.println("is"+ dnsServerIntf.dns(args[1])); } catch(Exception e){ System.out.println("Exception: "+e); }}}

DNSServer.java:
import java.net.*; import java.rmi.*; public class DNSServer { public static void main(String args[]){ try{ DNSServerImpl dnsServerImpl=new DNSServerImpl(); Naming.rebind("DNSServer", dnsServerImpl); } catch(Exception e){ System.out.println("Exception: "+e); }}}

DNSServerImpl.java:
Page | 47

import java.rmi.*; import java.rmi.server.*; import java.io.*; public class DNSServerImpl extends UnicastRemoteObject implements DNSServerIntf { public DNSServerImpl() throws RemoteException { } public String dns(String s) throws RemoteException { try{ FileInputStream fp= new FileInputStream("DNS.txt"); DataInputStream dp= new DataInputStream(fp); while(true) { String s1=dp.readLine(); if(s1.equals(s)) return dp.readLine(); dp.readLine(); } } catch (Exception e) { System.out.println("Exception :" +e); return "no info"; }}}

DNSServerIntf.java:
import java.rmi.*; public interface DNSServerIntf extends Remote{ String dns(String s) throws RemoteException; }

Page | 48

DNS.txt:
www.google.com 192.100.100.1 www.mjcollege.ac.in 192.100.100.2 www.gmail.com 192.100.100.3

Output:

Page | 49

11.

Program for creation of FTP Client for Uploading a file

FTPPut.java:
import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.StringTokenizer; import javax.swing.*; import javax.swing.border.*; import sun.net.TelnetInputStream; import sun.net.ftp.FtpClient; public class FTPPut extends JFrame { public static int BUFFER_SIZE = 10240; protected JTextField userNameTextField = new JTextField("anonymous"); protected JPasswordField passwordTextField = new JPasswordField(10); protected JTextField urlTextField = new JTextField(20); protected JTextField fileTextField = new JTextField(10); protected JTextArea monitorTextArea = new JTextArea(5, 20); protected JButton putButton = new JButton("Put"); protected FtpClient ftpClient; protected String localFileName; protected String remoteFileName; public FTPPut() { super("FTP Client"); JPanel p = new JPanel(); p.setBorder(new EmptyBorder(5, 5, 5, 5)); p.add(new JLabel("User name:")); p.add(userNameTextField); p.add(new JLabel("Password:")); p.add(passwordTextField); p.add(new JLabel("URL:")); p.add(urlTextField); p.add(new JLabel("File:")); p.add(fileTextField);
Page | 50

monitorTextArea.setEditable(false); JScrollPane ps = new JScrollPane(monitorTextArea); p.add(ps); JPanel p1 = new JPanel(new BorderLayout()); ActionListener lst = new ActionListener() { public void actionPerformed(ActionEvent e) { if (connect()) { Thread uploader = new Thread() { public void run() { putFile(); disconnect(); } }; uploader.start(); } } }; putButton.addActionListener(lst); p.add(putButton); getContentPane().add(p, BorderLayout.CENTER); WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { disconnect(); System.exit(0); } }; addWindowListener(wndCloser); setSize(720, 240); setVisible(true); }
Page | 51

public void setButtonStates(boolean state) { putButton.setEnabled(state); } protected boolean connect() { monitorTextArea.setText(""); setButtonStates(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); String user = userNameTextField.getText(); if (user.length() == 0) { setMessage("Please enter user name"); setButtonStates(true); return false; String password = new String(passwordTextField.getPassword()); String sUrl = urlTextField.getText(); if (sUrl.length() == 0) { setMessage("Please enter URL"); setButtonStates(true); return false; } localFileName = fileTextField.getText(); int index = sUrl.indexOf("//"); // Parse URL if (index >= 0) sUrl = sUrl.substring(index + 2); index = sUrl.indexOf("/"); String host = sUrl.substring(0, index); sUrl = sUrl.substring(index + 1); String sDir = ""; index = sUrl.lastIndexOf("/"); if (index >= 0) { sDir = sUrl.substring(0, index); sUrl = sUrl.substring(index + 1); }
Page | 52

remoteFileName = sUrl; try { setMessage("Connecting to host " + host); ftpClient = new FtpClient(host); ftpClient.login(user, password); setMessage("User " + user + " login OK"); setMessage(ftpClient.welcomeMsg); ftpClient.cd(sDir); setMessage("Directory: " + sDir); ftpClient.binary(); return true; } catch (Exception ex) { setMessage("Error: " + ex.toString()); setButtonStates(true); return false; } } protected void disconnect() { if (ftpClient != null) { try { ftpClient.closeServer(); } catch (IOException ex) { } ftpClient = null; } Runnable runner = new Runnable() { public void run() { putButton.setEnabled(true);
Page | 53

FTPPut.this.setCursor(Cursor .getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }; SwingUtilities.invokeLater(runner); } protected void putFile() { if (localFileName.length() == 0) { setMessage("Please enter file name"); } byte[] buffer = new byte[BUFFER_SIZE]; try { File f = new File(localFileName); int size = (int) f.length(); setMessage("File " + localFileName + ": " + size + " bytes"); FileInputStream in = new FileInputStream(localFileName); OutputStream out = ftpClient.put(remoteFileName); int counter = 0; while (true) { int bytes = in.read(buffer); if (bytes < 0) break; out.write(buffer, 0, bytes); counter += bytes; } out.close(); in.close(); } catch (Exception ex) { setMessage("Error: " + ex.toString()); } } protected void setMessage(final String str)
Page | 54

{ if (str != null) { Runnable runner = new Runnable() { public void run() { monitorTextArea.append(str + '\n'); monitorTextArea.repaint(); } }; SwingUtilities.invokeLater(runner); } } public static void main(String argv[]) { new FTPPut(); } }

Page | 55

12. Program for creation of FTP Client for Downloading a file FTPGet.java:
import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.StringTokenizer; import javax.swing.*; import javax.swing.border.*; import sun.net.TelnetInputStream; import sun.net.ftp.FtpClient; public class FTPGet extends JFrame { public static int BUFFER_SIZE = 10240; protected JTextField userNameTextField = new JTextField("anonymous"); protected JPasswordField passwordTextField = new JPasswordField(10); protected JTextField urlTextField = new JTextField(20); protected JTextField fileTextField = new JTextField(10); protected JTextArea monitorTextArea = new JTextArea(5, 20); protected JButton getButton = new JButton("Get");; protected FtpClient ftpClient; protected String localFileName; protected String remoteFileName; public FTPGet() { super("FTP Client -- GET"); JPanel p = new JPanel(); p.setBorder(new EmptyBorder(5, 5, 5, 5)); p.setLayout(new FlowLayout()); p.add(new JLabel("User name:")); p.add(userNameTextField); p.add(new JLabel("Password:")); p.add(passwordTextField); p.add(new JLabel("URL:")); p.add(urlTextField);
Page | 56

p.add(new JLabel("File:")); p.add(fileTextField); monitorTextArea.setEditable(false); JScrollPane ps = new JScrollPane(monitorTextArea); p.add(ps); ActionListener lst = new ActionListener() { public void actionPerformed(ActionEvent e) { if (connect()) { Thread downloader = new Thread() { public void run() { getFile(); // disconnect(); } }; downloader.start(); } } }; getButton.addActionListener(lst); p.add(getButton); getContentPane().add(p, BorderLayout.CENTER); WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { disconnect(); System.exit(0); } }; addWindowListener(wndCloser); setSize(720, 240); setVisible(true); }
Page | 57

public void setButtonStates(boolean state) { getButton.setEnabled(state); } protected boolean connect() { monitorTextArea.setText(""); setButtonStates(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); String user = userNameTextField.getText(); if (user.length() == 0) { setMessage("Please enter user name"); setButtonStates(true); return false; } String password = new String(passwordTextField.getPassword()); String sUrl = urlTextField.getText(); if (sUrl.length() == 0) { setMessage("Please enter URL"); setButtonStates(true); return false; } localFileName = fileTextField.getText(); // Parse URL int index = sUrl.indexOf("//"); if (index >= 0) sUrl = sUrl.substring(index + 2); index = sUrl.indexOf("/"); String host = sUrl.substring(0, index); sUrl = sUrl.substring(index + 1); String sDir = ""; index = sUrl.lastIndexOf("/"); if (index >= 0) { sDir = sUrl.substring(0, index); sUrl = sUrl.substring(index + 1); }
Page | 58

remoteFileName = sUrl; try { setMessage("Connecting to host " + host); ftpClient = new FtpClient(host); ftpClient.login(user, password); setMessage("User " + user + " login OK"); setMessage(ftpClient.welcomeMsg); ftpClient.cd(sDir); setMessage("Directory: " + sDir); ftpClient.binary(); return true; } catch (Exception ex) { setMessage("Error: " + ex.toString()); setButtonStates(true); return false; } } protected void disconnect() { if (ftpClient != null) { try { ftpClient.closeServer(); } catch (IOException ex) { } ftpClient = null; } Runnable runner = new Runnable() { public void run() { getButton.setEnabled(true);
Page | 59

FTPGet.this.setCursor(Cursor .getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }; SwingUtilities.invokeLater(runner); } protected void getFile() { if (localFileName.length() == 0) { localFileName = remoteFileName; SwingUtilities.invokeLater(new Runnable() { public void run() { fileTextField.setText(localFileName); } }); } byte[] buffer = new byte[BUFFER_SIZE]; try { FileOutputStream out = new FileOutputStream(localFileName); InputStream in = ftpClient.get(remoteFileName); int counter = 0; while (true) { int bytes = in.read(buffer); if (bytes < 0) break; out.write(buffer, 0, bytes); counter += bytes; } out.close(); in.close(); } catch (Exception ex) {
Page | 60

setMessage("Error: " + ex.toString()); } } protected void setMessage(final String str) { if (str != null) { Runnable runner = new Runnable() { public void run() { monitorTextArea.append(str + '\n'); monitorTextArea.repaint(); } }; SwingUtilities.invokeLater(runner); } } public static void main(String argv[]) { new FTPGet(); } }

Page | 61

13.

Program for creation of FTP Client for Listing of files

FTPList.java:
import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.StringTokenizer; import javax.swing.*; import javax.swing.border.*; import sun.net.TelnetInputStream; import sun.net.ftp.FtpClient; public class FTPList extends JFrame { public static int BUFFER_SIZE = 10240; protected JTextField userNameTextField = new JTextField("anonymous"); protected JPasswordField passwordTextField = new JPasswordField(10); protected JTextField urlTextField = new JTextField(20); protected JTextField fileTextField = new JTextField(10); protected JTextArea monitorTextArea = new JTextArea(5, 20); protected JButton fileList = new JButton("List"); protected FtpClient ftpClient; protected String localFileName; protected String remoteFileName; public FTPList() { super("FTP Client"); JPanel p = new JPanel(); p.setBorder(new EmptyBorder(5, 5, 5, 5)); p.add(new JLabel("User name:")); p.add(userNameTextField); p.add(new JLabel("Password:")); p.add(passwordTextField); p.add(new JLabel("URL:")); p.add(urlTextField); p.add(new JLabel("File:"));
Page | 62

p.add(fileTextField); monitorTextArea.setEditable(false); JScrollPane ps = new JScrollPane(monitorTextArea); p.add(ps); JPanel p1 = new JPanel(new BorderLayout()); fileList = new JButton("List"); ActionListener lst = new ActionListener() { public void actionPerformed(ActionEvent e) { if (connect()) { Thread downloader = new Thread() { public void run() { getList(); disconnect(); } }; downloader.start(); } } }; fileList.addActionListener(lst); p.add(fileList); getContentPane().add(p, BorderLayout.CENTER); WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { disconnect(); System.exit(0); } }; addWindowListener(wndCloser); setSize(720, 240); setVisible(true);
Page | 63

} protected boolean connect() { monitorTextArea.setText(""); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); String user = userNameTextField.getText(); if (user.length() == 0) { setMessage("Please enter user name"); return false; } String password = new String(passwordTextField.getPassword()); String sUrl = urlTextField.getText(); if (sUrl.length() == 0) { setMessage("Please enter URL"); return false; } localFileName = fileTextField.getText(); // Parse URL int index = sUrl.indexOf("//"); if (index >= 0) sUrl = sUrl.substring(index + 2); index = sUrl.indexOf("/"); String host = sUrl.substring(0, index); sUrl = sUrl.substring(index + 1); String sDir = ""; index = sUrl.lastIndexOf("/"); if (index >= 0) { sDir = sUrl.substring(0, index); sUrl = sUrl.substring(index + 1); } remoteFileName = sUrl; try { setMessage("Connecting to host " + host); ftpClient = new FtpClient(host); ftpClient.login(user, password);
Page | 64

setMessage("User " + user + " login OK"); setMessage(ftpClient.welcomeMsg); ftpClient.cd(sDir); setMessage("Directory: " + sDir); ftpClient.binary(); return true; } catch (Exception ex) { setMessage("Error: " + ex.toString()); return false; } } protected void disconnect() { if (ftpClient != null) { try { ftpClient.closeServer(); } catch (IOException ex) { } ftpClient = null; } Runnable runner = new Runnable() { public void run() { FTPList.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_C URSOR)); } }; SwingUtilities.invokeLater(runner); } protected void getList() { try
Page | 65

{ TelnetInputStream lst = ftpClient.list(); String str = ""; while (true) { int c = lst.read(); char ch = (char) c; if (c < 0 || ch == '\n') { str = str.toLowerCase(); { StringTokenizer tk = new StringTokenizer(str); int index = 0; while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (index == 6) // index of f.names(check the index on ftp) try { setMessage(token); } catch (NumberFormatException ex) { } index++; } } str = ""; } if (c <= 0) break; str += ch; } } catch (Exception ex) { setMessage("Error: " + ex.toString()); }
Page | 66

} protected void setMessage(final String str) { if (str != null) { Runnable runner = new Runnable() { public void run() { monitorTextArea.append(str + '\n'); monitorTextArea.repaint(); } }; SwingUtilities.invokeLater(runner); } } public static void main(String argv[]) { new FTPList(); } }

14.

NFS Configuration
Page | 67

Page | 68

Page | 69

You might also like