Pages

Tuesday, 21 February 2012

TCP/IP(Socket) Communication in Java Without Data Leakage

                During my early ages in java while implementing network data transferring using TCP/IP(socket communication)  i have experienced Data leakage, ie the total number of bytes of data transferred from Client System was not received at the server side. means data is completely send from the client system but it was not fully received at the server side because in between some bytes of data leakage has happened. After a long research  i came to know why it's happened.Now i would like to share my experience with you.


What is socket & Socket Communication

Definition

                    Socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.

1)On the client-side

                   The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.

On the server side

                  The server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

If everything goes well

        If the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server.The client and server can now communicate by writing to or reading from their sockets.

Problem
                 
        Suppose you have a device that makes readings and sends them to a computer through, for instance, a socket. If between two readings the computer has to do some calculations it is possible that, when the rate of the communication is higher, some data will be lost on the server side.


Solution

        To solve this situation, you can create a thread in the client side which only task is to take the data out of the socket and put it in a buffer where the main program will go read it as soon as he is able to. Besides, as you don't know witch is the best length for the buffer, it will be even better if the buffer can grow as it is needed.That's all about socket communication.


                               according to above statements and resarches I implemented an application for socket communication in a network  without data loss-age,and i put the source code here,The application contains 7 Files.

               1.ServerSystem.java
               2.ClientSystem.java
               3.IP.java
               4.PORT.java
               5.REQUEST.java
               6.FILE.java
               7.DIRECTORY.java

package com.socketcommunication.server;

/*
 * @(#)ServerSystem.java
 * Copyright (c) 2012, . All rights reserved.
 * author:riyo
 */
import java.io.OutputStream;
import com.socketcommunication.util.FILE;
import com.socketcommunication.util.PORT;
import com.socketcommunication.util.REQUEST;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/*
 * This is the Server Class .This class responsible for reading request from client
 * after reading request it will process acording to the request.
 * here what i did is that client will request for file and this class will read file from system and Send to
 * client through socket.
 */

public class ServerSystem implements Runnable {

    ServerSocket serverListenSocket = null;  //server listen socket

    public ServerSystem(int port) {
        try {
            serverListenSocket = new ServerSocket(port);  // PORT:7777
            new Thread(this).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            Socket clientSocket = null;
            while (true) {            //An inifinite loop Which used for listening the client requests
                System.out.println("(In 7777 Port )Server waiting . . .");
                clientSocket = serverListenSocket.accept();  //a communication socket created on accepting the server socket(handshakin process
                System.out.println("Client Connected.");
                new ClientHandler(clientSocket).start();       // when client connected An InnerClass That's
                //ClientHandler run method will start
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public class ClientHandler extends Thread {

        Socket serverSocket = null;    //Server bound socket.
        OutputStream out = null;       //outputstream used for write file content to client.
        DataInputStream din = null;    //datainputstram used for reading request from client.
        DataOutputStream dout = null;  //dataoutputstream used for writing filename to client.
        String CLIENT_REQUEST = null;  //String variable used for carry client request.
        File file = null;              //File Class used for creating instance of input file.
        FileInputStream fin;           //Inputstream used for reading data from input file.

        public ClientHandler(Socket serverSocket) {
            try {
                this.serverSocket = serverSocket;
                file = new File(FILE.EXAMPLE1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                out = serverSocket.getOutputStream();
                dout = new DataOutputStream(serverSocket.getOutputStream());
                din = new DataInputStream(serverSocket.getInputStream());

                CLIENT_REQUEST = din.readUTF().trim();
                System.out.println("CLIENT REQUEST:" + CLIENT_REQUEST);
                if (CLIENT_REQUEST.equals(REQUEST.FILE)) {
                    String fileName = getFileName();
                    sendFile(fileName);
                }
                if (CLIENT_REQUEST.equals(REQUEST.EXIT)) {
                    System.exit(0);  //will exit the entire application.
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void sendFile(String fileName) {

            try {
                fin = new FileInputStream(file);
                dout.writeUTF(fileName);          //send filename to client.
                dout.flush();                     //flush the stream.
                int bufferSize = serverSocket.getSendBufferSize();  //for getting the maximum byte value can send from the server bound socket
                System.out.println("Server Bound Socket Buffer size:" + bufferSize);
                byte bt[] = new byte[bufferSize];  //created a byte array with the size  max bound socket send size.
                int ch = 0;                        //variable will hold the data read by the inputstraem.
                while ((ch = fin.read(bt)) != -1) {
                    out.write(bt, 0, ch);// write read data to the clientsocket 1,byte array 2,the offset of byte array to start writing
                    // 3,ch: variable will carry the total read byte data size
                }
                closeStreamConnections();

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

        //Method used for get the input file name.This function will return the filename.
        private String getFileName() {
            String fileName = file.getName();
            return fileName;
        }

        //method used for closing all the open stream connections
        private void closeStreamConnections() {
            try {
                dout.close();
                out.close();
                fin.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("TCP/IP Communication System Without DataLossage:Dilvin Riyo   " + new Date().toLocaleString());
        new ServerSystem(PORT.SERVER_PORT);
    }
}

    

/*
 * @(#)ClientSystem.java
 * Copyright (c) 2012, . All rights reserved.
 * author:riyo
 */
package com.socketcommunication.client;

import com.socketcommunication.util.DIRECTORY;
import com.socketcommunication.util.IP;
import com.socketcommunication.util.PORT;
import com.socketcommunication.util.REQUEST;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.Socket;
import java.util.Date;

/*
 * This is the Client Class .This class will send request to server for data(here it's file).
 * server will send file and this class is responsible for reading fiecontent without dataloss.
 */
public class ClientSystem {

    private Socket clientSocket = null;
    private DataOutputStream dout = null;
    private DataInputStream din = null;
    private InputStream in = null;
    FileOutputStream fout = null;

    public ClientSystem(String serverIP, int serverPort) {
        try {
            clientSocket = new Socket(serverIP, serverPort);
            dout = new DataOutputStream(clientSocket.getOutputStream());
            in = clientSocket.getInputStream();
            din = new DataInputStream(in);
            getFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //This mathod responsible for read fileContent from server and create file with same name in loacl system.
    private void getFile() {
        try {
            dout.writeUTF(REQUEST.FILE);             //send file request to server
            System.out.println("Request send.");
            String fileName = din.readUTF().trim();  //got fileName of the file to be read
            System.out.println("Filename read.");
            int bufferSize = clientSocket.getReceiveBufferSize();  //recieve buffer size of the client.
            System.out.println("Client recieve buffer size=" + bufferSize);
            byte buffer[] = new byte[bufferSize];   //byte array used for reading data from server
            int ch = 0;                             //variable used for getting how much data read by the inputstram
            String outputFile = DIRECTORY.OUT_FILE_DIR + File.separator + fileName;   //output file
            fout = new FileOutputStream(new File(outputFile));
            while ((ch = in.read(buffer)) != -1) {  //This loop will execute till the stream ending.
                System.out.println(ch);
                fout.write(buffer, 0, ch);  // write read data to the file 1,byte array 2,the offset of byte array to start writing
                // 3,ch: variable will carry the total read byte data size
                fout.flush();
            }
            System.out.println("File Content reading over.");
            System.out.println("File Creation over (" + outputFile + "):)");
            closeStreamConnections();

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

    }

    //method used for closing all the open stream connections
    private void closeStreamConnections() {
        try {
            dout.close();
            in.close();
            din.close();
            fout.close();
            System.out.println("Connections closed.\n\n\t*************************************************************");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        System.out.println("TCP/IP Communication System Without DataLossage:Dilvin Riyo   " + new Date().toLocaleString());
        new ClientSystem(IP.SERVER_IP, PORT.SERVER_PORT);
    }
}


/*
 * @(#)IP.java
 * Copyright (c) 2012, . All rights reserved.
 * author:riyo
 */
package com.socketcommunication.util;

/**
 * This class is used for carry constant such as System IP.
 * Here it's used for carry server system IP.
 */
public class IP {

    public static final String SERVER_IP = "localhost";
}


/*
 * @(#)PORT.java
 * Copyright (c) 2012, . All rights reserved.
 * author:riyo
 */
package com.socketcommunication.util;

/**
 * This class is used for carry constant such as System ports.
 * Here it's used for carry server listen ports.
 */
public class PORT {

    public static final int SERVER_PORT = 7777;
}


/*
 * @(#)REQUEST.java
 * Copyright (c) 2012, . All rights reserved.
 * author:riyo
 */
package com.socketcommunication.util;

/**
 * This class is used for carry constant such as System Requests.
 * Here it's used for carry client requests.
 */
public class REQUEST {

    public static final String FILE = "1";
    public static final String EXIT = "0";
}


/*
 * @(#)FILE.java
 * Copyright (c) 2012, . All rights reserved.
 * author:riyo
 */
package com.socketcommunication.util;

/**
 * This class is used for carry constant such as File paths
 * Here it's used for carry input file path.
 */
public class FILE {

    public static final String EXAMPLE1 = "C:\\Documents and Settings\\admin\\Desktop\\test.mp4";
}



/*
 * @(#)DIRECTORY.java
 * Copyright (c) 2012, . All rights reserved.
 * author:riyo
 */
package com.socketcommunication.util;

/**
 *This class is used for carry constant such as DIRECTORY paths
 * Here it's used for carry output folder path.
 */
public class DIRECTORY {

    public static final String OUT_FILE_DIR = "C:\\Documents and Settings\\admin\\Desktop\\TEST";
}



                      I commented out in the whole code,so that you can understand easily.Please give me your feedbacks,i love getting positive feedback, but i need to know what you don't like too,i am always working to improve , so i want to know what you felt.

Download all source code here.

Happy Blogging.


Thursday, 9 February 2012

Proxy Server Implementation using JAVA in a Client-Server Architecture


       First of all i would like to thank you for reading my article,and i wish to tell you that this is my FIRST post. I have done this proxy server implementation in one of my projects titled 'ANTIPHISHING SYSTEM' and this will be use full for all of you .If you Like the post please comment it and let me know valuable suggestions , all appreciations and criticisms are invited . Thank you .

1)Before running this application first you have to Configure your Browser In the way shown below .(The picture below is only for Firefox user's)




2)The Application contains 4 Files.

         *ClientProxy.java
         *RequestHandler.java
         *ResponseHandler.java
         *SETTINGS.java


 /*  
  * @(#)ClientProxy.java  
  *  
  * Copyright (c) 2012, . All rights reserved.  
  *  
  */  
 import java.net.*;  
 /*  
  * This is the main Class .This class responsible for reading user equest from browser,  
  * after reading request it will send request to RequestThraed.java  
  * pls do Browser setiings before running this application  
  */  
 public class ClientProxy implements Runnable {  
   ServerSocket browserSocket = null;  
   Socket outputSocket = null;  
   Socket inputSocket = null;  
   String serverIP = SETTINGS.SERVER_IP;  
   int serverPort = SETTINGS.SQUID_PORT;  
   public ClientProxy(int port) {  
     try {  
       browserSocket = new ServerSocket(port);  
       run();  
     } catch (Exception ex) {  
       ex.printStackTrace();  
     }  
   }  
   public void run() {  
     try {  
       System.out.println("Proxy Server Started...");  
       while (true) {  
         inputSocket = browserSocket.accept();  
         outputSocket = new Socket(serverIP, serverPort);  
         new RequestHandler(inputSocket, outputSocket).start();  
         new ResponseHandler(outputSocket, inputSocket).start();  
       }  
     } catch (Exception ex) {  
       ex.printStackTrace();  
     }  
   }  
   public static void main(String[] args) {  
     new ClientProxy(SETTINGS.BROWSER_REQUEST_PORT); //browser request will come here ... :)  
   }  
 }  


 /*  
  *@(#)RequestHandler.java  
  * author:riyo  
  *Copyright (c) 2012, . All rights reserved.  
  *  
  */  
 import java.io.*;  
 import java.net.*;  
 /*  
  * This class responsible for reading user equest from clientProxy .  
  * after reading request it will send request to squid port in server system.  
  */  
 public class RequestHandler extends Thread {  
   Socket inputSocket = null;  
   Socket outputSocket = null;  
   InputStream in = null;  
   OutputStream out = null;  
   String request = "";  
   public RequestHandler(Socket in, Socket out) {  
     try {  
       inputSocket = in;  
       outputSocket = out;  
     } catch (Exception ex) {  
       ex.printStackTrace();  
     }  
   }  
   @Override  
   public void run() {  
     try {  
       in = inputSocket.getInputStream();  
       out = outputSocket.getOutputStream();  
       while (true) {  
         byte[] b = new byte[10000];  
         int len = in.read(b);  
         if (len == -1) {  
           in.close();  
           out.close();  
           break;  
         }  
         request = new String(b, 0, len);  
         System.out.println("***************************REQUEST***************************");  
         System.out.println(request);  
         out.write(b, 0, len);  
         System.out.println("request send to server.");  
       }  
     } catch (Exception e) {  
       System.out.println(e);  
     }  
   }  
 }  




 /*  
  *@(#)ResponseHandler.java  
  *Copyright (c) 2012, . All rights reserved.  
  *author:riyo  
  */  
 import java.io.*;  
 import java.net.*;  
 /*  
  * This class responsible for reading response from Server .  
  * after reading response it will write response in browser.  
  */  
 public class ResponseHandler extends Thread {  
   Socket inputSocket = null;  
   Socket outputSocket = null;  
   InputStream in = null;  
   OutputStream out = null;  
   public ResponseHandler(Socket in, Socket out) {  
     try {  
       inputSocket = in;  
       outputSocket = out;  
     } catch (Exception ex) {  
       System.out.println("Error: " + ex);  
     }  
   }  
   @Override  
   public void run() {  
     try {  
       in = inputSocket.getInputStream();  
       out = outputSocket.getOutputStream();  
       while (true) {  
         byte[] b = new byte[10000];  
         int len = in.read(b);  
         if (len == -1) {  
           in.close();  
           out.close();  
           break;  
         }  
         out.write(b, 0, len);  
         System.out.println("response written to firefox.");  
         System.out.println("***************************END***************************\n\n\n");  
       }  
     } catch (Exception e) {  
       System.out.println(e);  
     }  
   }  
 }  



 /*  
  *@(#)SETTINGS.java  
  *Copyright (c) 2012, . All rights reserved.  
  *author:riyo  
  */  
 public class SETTINGS {  
   public static final String SERVER_IP = "192.168.1.100"; //This is the Server Ip in My Network  
   public static final int SQUID_PORT = 3128; //This is the SQUID Application Running Port in Server System.  
   public static final int BROWSER_REQUEST_PORT = 9999; //In This port all browser request are coming ...  
 }  



3)Run the main Class that is ClientProxy.java .

4)Connect to a URL using your Browser That's it. :)

5)Thank you,visit Again.

*Download full source code Here