Saturday, 22 November 2014

What is a Singleton Class in Java ?

Singleton Class

    The Class which allows only to create a single object is known as singleton class in java. First time it will create an object and second time onward it will return the same object which is created earlier. This class object can be created only through a factory method, because it's constructor is private.

Example

package com.els.core;
import java.io.Serializable;

public class SingleObject implements Cloneable, Serializable
{
//create an object of SingleObject  
private static SingleObject instance =null;

//make the constructor private so that this class cannot be instantiated
private SingleObject()
{
//arguments
System.out.println("Singleton object created...");
}
//Get the only object available  
public static SingleObject getInstance() throws Exception
{
if(instance==null)
{
instance= new SingleObject();
}
return instance;
}
//non static method
public void showMessage()
{
System.out.println("Singleton Class!");
}
}

******

package com.els.core;

//creating object of singleton class
public class SingleTest
{

public static void main(String[] args)
{
try{
                        //first time creating object
SingleObject obj1 = SingleObject.getInstance();

                        //second time
SingleObject obj2 = SingleObject.getInstance();

System.out.println(obj1);
System.out.println(obj2);

                        obj1.showMessage();

}catch(Exception e){
e.printStackTrace();
}
}  

}

Compile both class and execute.

javac SingleObject 
javac SingleTest

java com.els.core.SingleTest

Output

Singleton object created...
com.els.core.SingleObject@f9f9d8
com.els.core.SingleObject@f9f9d8
Singleton Class!

Note : But the above class is not fully singleton class. We will discuss on next topic. Please share your feedback as comment.

Monday, 6 October 2014

What is networking in Java ? How to write a client-Server console program using a Java ?

 

Networking in Java

Ans :- Connecting one node(socket) of one computer with another node of same or other computer is called as networking. Basically it is useful to sending data from one socket to another socket/node of computer. Using java networking we can connect one socket with another. It is suitable for sending some data to other program and receiving data form others. Generally all chatting application like social networking websites works on it. Let us see the following chatting application.

Server.java

import java.io.*;
import java.net.*;
public class Server
{
  public static void main(String[] args) throws Exception
  {
      ServerSocket servsock = new ServerSocket(3000);
      System.out.print("\n\n Hello ! Now Server is ready for chatting ......... \n\n :\t");
      Socket sock = servsock.accept( );                         
     
      //prepare object to reading data from keyboard (BufferReader object)
      BufferedReader keyboardRead = new BufferedReader(new InputStreamReader(System.in));
      //prepare object to sending data to Client Program (PrintWriter object)
      OutputStream os = sock.getOutputStream();
      //object to send data to Server(PrintWriter object)
      PrintWriter pw = new PrintWriter(os, true);

     //prepare object to receiving data from Client Program ( InputStream  object)
      InputStream is = sock.getInputStream();
      //object to read from Client ( BufferReader  object)
      BufferedReader receiveRead = new BufferedReader(new InputStreamReader(is));

      String receiveMessage, sendMessage;   
  
      //Processing for chatting:-
      while(true)
      {
       // reading data from Client :-
        if((receiveMessage = receiveRead.readLine()) != null) 
        {
           System.out.println(receiveMessage); // displaying received data at DOS prompt/console       
        }        
 
          // reading data from KeyBoard:-
         sendMessage = keyboardRead.readLine();
         // sending data to Client Program:-
         pw.println(sendMessage);            
 
         //flush data:-
        pw.flush();
      }              
    }                   
}
 

Client.java

import java.io.*;
import java.net.*;
public class Client
{
  public static void main(String[] args) throws Exception
  {
     String receiveMessage, sendMessage;  

     Socket sock = new Socket("127.0.0.1", 3000); //socket is ready for localhost/port no 127.0.0.1
    
     //prepare object to reading data from keyboard (BufferReader object) :-     BufferedReader keybordRead = new BufferedReader(new InputStreamReader(System.in));
    
     //prepare object to receiving data from Server Program (InputStream  object) :-
     InputStream is = sock.getInputStream();
     //object to read data from Server (BufferReader object)
     BufferedReader receiveRead = new BufferedReader(new InputStreamReader(is));
 
     //prepare object to sending data to Server Program (OutputStream object) :-
     OutputStream os = sock.getOutputStream();
     //object to send data to Server (PrintWriter object)
     PrintWriter pw = new PrintWriter(os, true);
 
     //user confirmation message:-
     System.out.print("\n\n Please ensure that Server application is already running, then start the    chatting.....\n\n :\t");

    //Processing for Chatting:-
     while(true)
     {
    
       // reading data from KeyBoard:-
        sendMessage = keybordRead.readLine(); 
       // sending data to the Server Program:-
        pw.println(sendMessage);    

       // flush the data
        pw.flush();                  

       // receive data from Server
        if((receiveMessage = receiveRead.readLine()) != null)
        {
            System.out.println(receiveMessage); // displaying received data at DOS prompt/console
        }        
    }              
  }                   
}
 
Note:-
  1. First compile both application using "javac" tool.
  2. Open two different command prompt.
  3. First run the Server program in one command prompt.
  4. Then run the Client program in another command prompt.
  5. Send the message from Client application and receive message on Server program.
  6. Then send the message from Server program and receive these message on Client.
Now you can feel the chatting using networking techniques in Client-Server application...

Note : We will discuss on next topic. Please share your feedback as comment.