Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Saturday, February 13

RPC Sample code in Java



Hello friends,
In this post we will see how RPC (Remote Procedure Call) mechanism can be implemented in Java.
RMI (Remote Method Invocation)  is the special mechanism to do  RPC in Java. RMI is the java flavor of RPC in other languages, but core concept is still same!

The main Idea is summarized as below:

 In this example, we make a server (RMIServer.java) to receive input text from client application and replies how many characters it received.


Server Side:
  • Create a remote interface. (myInterface.java)
  • Create a separate java file to implement the remote interface. (RMIServer.java)
  • Register the interface in RMI registry (bind with any name eg: myRMIService)
Client Side:
  • In client code, through interface name (in our case myRMIService) create a "fake remote" object reference of server within client. (RMIClient.java)
  • Through this reference access the server methods / services


Let us have a detailed look on code:

1. MyInterface.java

  1. import java.rmi.*;
  2. public interface MyInterface extends Remote
  3. {
  4.  public String countInput(String input)throws RemoteException;   
  5. }

  • It simply says about a remote service to accept a string input and gives string output.
  • Line no 4  insists that any code implementing this interface should have countInput method.

2. RMIServer.java
  1. import java.rmi.*;
  2. import java.rmi.server.*;
  3. public class RMIServer extends UnicastRemoteObject implements MyInterface
  4.     public RMIServer()throws RemoteException
  5.     { 
  6.         System.out.println("Remote Server is running Now.!!"); 
  7.     }    
  8. public static void main(String arg[])
  9.     try{ 
  10.         RMIServer p=new RMIServer();
  11.         Naming.rebind("rmiInterface",p);
  12.     }  
  13. catch(Exception e)
  14. { System.out.println("Exception occurred : "+e.getMessage()); } 
  15. }

  16.     @Override
  17.     public String countInput(String input) throws RemoteException 
  18.     {
  19.     System.out.println("Received your input "+ input+"  at server!!");
  20.         String reply;
  21.         reply="You have typed "+ input.length() +"  letters!!";
  22.         return reply;
  23.     }
  24. }
  • Line 3 says we are going to implement MyInterface interface
  • Line 13 says we register this service with name rmiInterface. Any client can access the services from this class using this name.
  • Line 19-27 implements the methods offered by interface.
3. RMIClient.java
  1. import java.rmi.*;
  2. import java.io.*; 
  3. public class RMIClient
  4. {   
  5.     public static void  main(String args[])
  6.     { 
  7.         try
  8.       { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
  9.       MyInterface p=( MyInterface)Naming.lookup("rmiInterface");
  10.         System.out.println("Type something..."); 
  11.         String input=br.readLine(); 
  12.         System.out.println(p.countInput(input)); 
  13.             }
  14.         catch(Exception e) { 
  15.             System.out.println("Exception occurred : "+e.getMessage());
  16.         }
  17.     } 
  18.  
Line 9:  Looking for the remote service using the name!
Line 12: Accessing the service using the remote object.

RESULT:


Compile the java files.



Run remote object registry  called  rmiregistry. It is used by RMI servers on the same host to bind remote objects to names.


Run the Server class.

Run the client class. You can see it is prompting for input


Type some text
Input is received by remote server
   
                                          


Client receives reply from remote server



Hope this post was useful!!


Feel free to post your suggestions and comments!

Monday, January 16

COMPRESS A FILE INTO .gz FILE ~ COMPLETE JAVA CODE






Hello friends,

In this post I’m presenting a java code to compress a file into -.gz format.
Hope this will be useful to you..!!!

Algorithm
1.      1.Input the name of the file to be zipped.
2.      Create an OutputStream in the name of given _file.gz.
3.      Point it to the GZIPOutputStream.
4.       Read from the file to be zipped, bytewise, and write it into GZIPOutputStream.



import java.io.*;
import java.util.zip.*;
public class CompressFile {
public static void compresser(String temp) {
try {
File file = new File(temp);
FileOutputStream fout = new FileOutputStream(file + ".gz");
GZIPOutputStream gout = new GZIPOutputStream(fout);
FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin);
byte[] buffer = new byte[1024];
int i;
while ((i = in.read(buffer)) >= 0) {
gout.write(buffer, 0, i);
}
System.out.println(" successfully compressed");
in.close();
gout.close();
}
catch (IOException e) {
System.out.println("Exception is" + e);
}
}
public static void main(String args[]) {
if (args.length != 1) {
System.out.println("Please enter the file name which needs to be compressed ");
} else {
compresser(args[0]);
}
}
}





For compiling::
javac CompressFile.java




For running::
java CompressFile any_file_name_present_in_current_directory


Tuesday, December 20

Develop a Simple Game in Java - Complete code


Hi Friends,
Here I’m posting about my first Java game  ~ HitME..!!! Through this post you will understand about:
·         Concept of Java Threads.
·         Codes for Jframe and other components.
·         Java code to close a window.
·         Actions related to Buttons and Button Array.
·         Random Number generation in Java.
HitME is the Java game in which several Buttons will be provided within  a frame. To win the game, you have to click the Button when it become Green in color.  Only 5 chances are allowed after that you will loose the game.

Without much “blah-blahs” on theoretical backgrounds, it will be better to get into the code.
Here we go..!!!!(Complete code is given at the  end of this post)

1.       import javax.swing.*;
2.       import java.awt.*;
3.       import java.awt.event.*;
4.       import java.util.Random;
Import all necessary packages. Swing and awt( 1 and 2) for graphics,subpackage awt.event(3) for event handling and util.Random(4) for the Random number generation.
·         Codes for Jframe and other components.

5.       class GameFrame extends Thread implements ActionListener
6.       {
a.       int i,n=0,Chances=5;
b.      JFrame f;
c.       JLabel chanceLabel;
d.      JButton b[]=new JButton[50];
e.      Random currButton=new Random();
  
The class GameFrame defines the design of our Game. In line (5) we inherited Thread Base class( to use Thread)and used interface ActionListener. We should override its abstract method actionPerformed(ActionEvent a) (to recognize ButtonClick and other actions, Deep notion of them is not necessary here)
Apparently (5.a) defines total no:of chances, (5.c) defines Frame and so on.


7.       GameFrame() {
                                                               i.      f=new JFrame("GAME");
                                                             ii.      f.setSize(600,400);
                                                            iii.      f.setLayout(new FlowLayout());
8.       for(i=0;i<49;i++)
9.       {
b.      b[i]=new JButton("HIT ME");
c.       b[i].setActionCommand("Button"+i);
d.      b[i].addActionListener(this);
e.      b[i].setForeground(Color.blue);
f.        f.add(b[i]);         
10.   }
11.   chanceLabel =new JLabel("\n\n\nCHANCES LEFT :"+Chances);
12.   f.add(chanceLabel);
13.   f.setVisible(true);
Within the constructor of GameFrame, we defined the structure
  • Statements  (7.i) to(7.iii) are only  for Frame.
  • Statements 8 and 9 generates 49 buttons, 9.c sets a unique string with each Button with setActionCommnad () to identify which button has been clicked.
  • 9.e to give color to Button. Several options for colors are available as gree,magenta, balck etc.
  • We added all Buttons in line 9.f.
  • In 12 we added a Label to show the number of chances left.
  • In 13, we made visibility true, which is a very important step.
·         Java code to close a window.

14.   f.addWindowListener(new WindowAdapter() {
15.   public void windowClosing(WindowEvent e) {
16.   System.exit(0);
17.   stop();
18.   }});
16-18 is the code to close the window.

·         Concept of Java Threads.
·         Random Number generation in Java.

19.public void run()
a.       {
                                                               i.      try
                                                             ii.      {
                                                            iii.      while(true)
                                                           iv.      {
                                                             v.      n=currButton.nextInt(49);
                                                           vi.      b[n].setForeground(Color.green);
                                                          vii.      sleep(600);
                                                        viii.      b[n].setForeground(Color.blue);
                                                           ix.      }
                                                             x.      }
                                                           xi.      catch(Exception e)
                                                          xii.      {
                                                        xiii.      }}
The code that should be executed by Thread is given in run() method.
  • Here we needed to generate random numbers so that Button are made Green at random. To do so while made an endless while loop(19.a.iii)
  •  currButton  is an Object of Random class imported as  import java.util.Random. currButton.nextInt(49) yield a random number between 0 1nd 49 so that we can choose any button at random.(19.a.v).
  • Set the button color(vi).
  • To persist the green color for some time we make Thread inactive by sleep()  (vii)
  • After that particular time we made the button  to prior state by setting default color.(viii)
  • Since sleep() is an error generating method we should include this fragment in try-catch block.

Handle Button Click
19.   public void actionPerformed(ActionEvent a)
a.       {
b.      String s="Button"+n;
c.       if(!s.equals(a.getActionCommand()))
d.      {
e.      if(Chances>1)
f.        {
g.       Chances--;
h.      chanceLabel.setText("\n\n\nCHANCES LEFT :"+Chances);
i.         }
j.        else
k.       {
l.         JOptionPane.showMessageDialog(f," BETTER LUCK NEXT TIME.!!!YOU LOSE");
m.    System.exit(0);
n.      stop();
o.      }             

p.      }
q.      else
r.        {
s.       JOptionPane.showMessageDialog(f,"CONGRATULATIONS!!!!!YOU WIN");
t.        stop(); 
u.      }             
v.       }
w.     }

Here we define the abstract method actionPerformed () which will be active whenever a Button is clicked.
  • String s="Button"+n; store the code for exact button Green active at that time as n points to the active Button. For eg, if 5 th Button is Green at present, s will be “Button 5”.<b>
  • a.getActionCommand() will return the string associated with clicked button< for eg: it return Button 3 if we clicked third Button).  <c>
  • If wrong Button is clicked, if condition in <c> is valid and check the no: of chances left. Disply it in a label< h>
  • If all chances are over, pop up a messageBox  <l>
  • If correct button is clicked Display a winner meassage <s>

NB: If we close the main process<ie, our frame> the Thread will continue its work in background.  To avoid this at the moment one wins or looses, the thread should be terminated usind stop().
See lines(19.n) and (19.t)

20.class HitMe
{
a.       public static void main(String a[])
b.      {
                                                               i.      GameFrame x=new GameFrame();
                                                             ii.      x.start();

c.       }
b.      }
 At last make another class(It should contain a main()class) to invoke this GameFrame .
20.i  calls the constructor.
20.ii will make the Thread runnable. Using start() method.

 The complete code is as follows:


HitME.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

class GameFrame extends Thread implements ActionListener
{
 int i,n=0,Chances=5;
 JFrame f;
 JLabel chanceLabel;
 JButton b[]=new JButton[50]; 
 Random currButton=new Random();
 

GameFrame()
 {
  f=new JFrame("GAME");
  f.setSize(600,400);
  f.setLayout(new FlowLayout()); 


for(i=0;i<49;i++)
{
 b[i]=new JButton("HIT ME");
 b[i].setActionCommand("Button"+i);
 b[i].addActionListener(this);
 b[i].setForeground(Color.blue);
 f.add(b[i]);
}


JOptionPane.showMessageDialog(f,"HIT ME GAME\nClick Green Button To WIN..!!!!\n Total Chances: 5");

chanceLabel =new JLabel("CHANCES LEFT :"+Chances);
f.add(chanceLabel);

f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
      System.exit(0);
      stop();
    }});

 }


 public void run()
 {
  try
  {
  while(true)
  {
  n=currButton.nextInt(49);
  b[n].setForeground(Color.green);
  sleep(600);
  b[n].setForeground(Color.blue);
  }


  }
  catch(Exception e)
  {}
 }


 public void actionPerformed(ActionEvent a)
 {
   
 String s="Button"+n;
 if(!s.equals(a.getActionCommand()))
 {
  if(Chances>1)
  {
  Chances--;
  chanceLabel.setText("CHANCES LEFT :"+Chances);
  }
  else
  {
   JOptionPane.showMessageDialog(f,"BETTER LUCK NEXT TIME.!!!\nYOU LOSE");
     System.exit(0);
   stop();
  }

 }
 else
 {
  JOptionPane.showMessageDialog(f,"CONGRATULATIONS!!!!!YOU WIN");

 System.exit(0);
  stop(); }
 }
}



class HitME
{
 public static void main(String a[])
 {
  GameFrame x=new GameFrame();
  x.start();


 }
}




 I hope this post was useful for you.!! I'm waiting for youe valuable suggestions. Please comment here ur Feedback..!!
Thank you..!
Bye..!!  :)