Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

Create your own Simple File Transfer App over LAN (with Source code in JAVA)

Many Core Java packages can be used to create useful applications. This application uses java.net package to establish connection between two systems residing on the same network.  This point is important, because it will not work for arbitrary networks (having no connection between them). For those who don't have basic networking knowledge, in the simplest language same network means computer systems connected through the same router, or directly connected to each other via LAN Wire.

Networking Basics : When we connect to a network (a router), we get an IP from the router, which is usually of the form xxx.xxx.x.x, where x is a no. between 0 to 255 like 192.168.1.5 or 192.168.0.5 . Usually the first address in the series is of the router itself, i.e. 192.168.1.1.
In networking, there is a simple concept of a socket which is the combination of IP Address and Port number. Port no. is a is a no. between 0 to 65535. Out of this, 0 to 1023 are reserved for specific services and 1024 to 65536 can be used for our codes. In java, there are two classes which help in communication via these ports. These are namely, java.net.Socket and java.net.ServerSocket.  Socket acts as a client and ServerSocket acts as a server.

This simple software uses these two classes to send and receive files. ServerSocket opens a port on a system and waits for a client to connect to that port. On the other end, a system on the same network uses Socket class to connect to this device to establish connection and recieve data. The serveris currently able to send one file at a time to client.

The image shown below shows both the Client and Server side applications :

server

The Server Side Application has options to select the file to be sent and then press the button "Send File". For the client side, it has a text field where we enter the address specified by the server (which is 192.168.1.6 here). The default location where the client saves the file is Desktop of the user but the user can change the path where these files are saved after downloading. But, protected paths like C: and C:Program Files should be avoided as the destination paths, else an error is shown and Client shutdowns. The default location is then reset again to Desktop.

A simple setup using Batch script, VB Script,Registry Script and Winrar was created to deploy the JAR file onto Windows Systems both 32 and 64 bit. JRE/ JDK 1.4 or above should be installed to use this application. You can try this application on your same system (local server) by using 127.0.0.1 as server address on client side.After installation on windows system, you will get these options on Right Click of each file/folder (called as context menu), which allows instant sharing as shown below.

Screenshot of Installed Program

Download the application from here

**SOURCE **

Client side source code (Client.java) :

import java.util.StringTokenizer;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Client extends JFrame implements ActionListener
{
    JTextField address;
    JButton recieve;
    JLabel status,title;
    int screenX,screenY,myX,myY;
    JPanel lowerBorder;
    JProgressBar jpb;
    String location; // represents location where downloaded file is to be saved
    private void setFont(Font f,JComponent...c)
    {
        for(JComponent C:c)
            C.setFont(f);
    }
    private void add(JComponent parent,JComponent component,int gridx, int gridy, int gridwidth, int gridheight,int posInCell,Insets insets)
    {
        parent.add(component, new GridBagConstraints(gridx, gridy,gridwidth, gridheight, 1.0, 1.0, posInCell, GridBagConstraints.NONE, insets, 0,0));
    }
    Client()
    {

        // set Windows Look and Feel for Windows Systems
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null,"Using Swing Default Look and Feel, as you a using a NON-WINDOWS System","Changing look and feel",0);
        }
        JButton cross,minimize;
        JPanel upperBorder,panel,flowPanel;
        JFileChooser jfc;
        final JLabel defaultLocation = new JLabel("Default location is : "+(location=defLoc()));
        final JLabel changeLocation = new JLabel("Change Location where downloaded file is saved ");

        address   = new JTextField("Enter Address as specified by Server");
        recieve   = new JButton("Recieve File");
        (cross    = new JButton("X")).setForeground(new Color(170,111,236));
        (minimize = new JButton("-")).setForeground(new Color(170,111,236));
        (status   = new JLabel("Enter Server Adress and press 'Recieve File' to Continue")).setForeground(Color.WHITE);
        (title    = new JLabel("  Smart File Transfer (Client)")).setForeground(Color.WHITE);
        jfc       = new JFileChooser();

        jpb = new JProgressBar();
        jpb.setStringPainted(true);
        jpb.setFont(new Font("Times new roman",Font.BOLD,20));
        jpb.setForeground(new Color(170,111,236));
        jpb.setBackground(Color.BLACK);

        panel     = new JPanel()
        {
            protected void paintComponent(Graphics g)
            {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                g2d.setPaint(new GradientPaint(0, 0,new Color(170,111,236), 0, getHeight(),new Color(170,111,236)));
                g2d.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        (upperBorder = new JPanel()).setBackground(Color.BLACK);
        (lowerBorder = new JPanel()).setBackground(Color.BLACK);
        (flowPanel   = new JPanel()).setBackground(Color.BLACK);

        setFont(new Font("Times new roman",Font.PLAIN,20),status,recieve,title);
        setFont(new Font("tahoma",Font.BOLD,20),cross,minimize);
        setFont(new Font("Times new roman",Font.PLAIN,26),address);

        panel.setLayout(new GridBagLayout());
        upperBorder.setLayout(new BorderLayout());
        lowerBorder.setLayout(new FlowLayout(FlowLayout.CENTER));

        add(panel,address,0,0,1,1,GridBagConstraints.CENTER,new Insets(10,10,10,10));
        add(panel,recieve,0,1,1,1,GridBagConstraints.CENTER,new Insets(10,10,10,10));
        add(panel,defaultLocation,0,2,3,1,GridBagConstraints.WEST,new Insets(0,0,0,0));
        add(panel,changeLocation,0,3,3,1,GridBagConstraints.WEST,new Insets(0,0,0,0));

        flowPanel.add(minimize);
        flowPanel.add(cross);
        upperBorder.add(flowPanel,BorderLayout.EAST);
        upperBorder.add(title); // not centered, towards left.
        lowerBorder.add(status);
        add(panel);
        add(upperBorder,BorderLayout.NORTH);
        add(lowerBorder,BorderLayout.SOUTH);
        final JTextField temp=address;
        addMouseListener(new MouseAdapter()
        {
            public void mousePressed(MouseEvent me)
            {
                screenX = me.getXOnScreen();
                screenY = me.getYOnScreen();
                myX     = getX();
                myY     = getY();
            }
        });
        addMouseMotionListener(new MouseMotionAdapter()
        {
            public void mouseDragged(MouseEvent me)
            {
                int deltaX = me.getXOnScreen() - screenX;
                int deltaY = me.getYOnScreen() - screenY;
                setLocation(myX + deltaX , myY + deltaY);
            }
        });
        address.addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent me)
            {
                temp.setText("");
                temp.removeMouseListener(this);
            }
        });
        changeLocation.addMouseListener(new MouseAdapter()
        {
            public void mouseEntered(MouseEvent me)
            {
                changeLocation.setForeground(Color.WHITE);
            }
            public void mouseExited(MouseEvent me)
            {
                changeLocation.setForeground(Color.BLACK);
            }
            public void mouseClicked(MouseEvent me)
            {
                JFileChooser jfc = new JFileChooser();
                jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                jfc.setCurrentDirectory(new File(location));
                int ret = jfc.showSaveDialog(null);
                if(ret == JFileChooser.APPROVE_OPTION)
                {
                    try
                    {
                        FileWriter fw = new FileWriter("c:\sft\log.bin");
                        fw.write(jfc.getSelectedFile().toString());
                        fw.close();
                        defaultLocation.setText("Default Location is : "+(location=jfc.getSelectedFile().toString()));
                    }
                    catch(Exception e)
                    {
                         JOptionPane.showMessageDialog(null,"Error in changing path, The application will now exit","Fatal Error",0);
                    }
                }
            }
        });
        recieve.addActionListener(this);
        cross.addActionListener(this);
        minimize.addActionListener(this);
        setResizable(false);
        setUndecorated(true);
        setSize(600,300);
        getRootPane().setBorder(BorderFactory.createLineBorder(new Color(170,111,236),5));
        getRootPane().setDefaultButton(recieve);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
        requestFocus();
    }
    private String defLoc()
    {
        String ret="";
        try
        {
            BufferedReader br  = new BufferedReader(new FileReader("c:\sft\log.bin"));
            String s = br.readLine();
            ret=s;
            File f = new File(s);
            if(!f.isDirectory())
                new FileReader(s);
        }
        catch(Exception e)
        {
            if(e instanceof FileNotFoundException || e instanceof NullPointerException)
            {
                try
                {
                    FileWriter fw = new FileWriter ("c:\sft\log.bin");
                    ret = System.getProperty("user.home")+"\Desktop\";
                    fw.write(ret);
                    fw.close();
                }
                catch(Exception ee)
                {
          JOptionPane.showMessageDialog(null,"Critical Error, The application will now exit","Critical Error",0);
                }
            }
        }
        return ret;
    }
    public void actionPerformed(ActionEvent ae)
    {
        String com=ae.getActionCommand();

        if(com.equals("-"))
            setState(JFrame.ICONIFIED);
        else if(com.equals("X"))
            System.exit(0);
        else if (com.equals("Recieve File"))
        {
            recieve.setEnabled(false);
            int add[] = new int[4];
            int counter=0;
            StringTokenizer st = new StringTokenizer(address.getText(),".");
            while(st.hasMoreTokens())
            {
                try
                {
                    if(counter>=4)
                        new Integer("g");
                    add[counter++]=new Integer(st.nextToken());
                }
                catch(NumberFormatException nfe)
                {
                    address.setText("");
                    recieve.setEnabled(true);
                    JOptionPane.showMessageDialog(null,"IP address has only no.s seperated by dots (.)nIt is of the form "xxx.xxx.xxx.xxx" nwhere xxx is a no. less than 256","Integer Data Expected",0);
                    return;
                }
            }
            if(  !(counter == 4) || add[0] > 255 || add[1] > 255 || add[2] > 255 || add[3] > 255 )
            {
                address.setText("");
                recieve.setEnabled(true);
                JOptionPane.showMessageDialog(null,"Incorrect IP Address nIt is of the form "xxx.xxx.xxx.xxx" nwhere xxx is a no. less than 256","Invalid IP",0);
                return;
            }
            new Thread(new Runnable()
            {
                public void run()
                {
                    recieveFile();
                }
            }).start();
        }
    }
    private void recieveFile()
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                status.setText("Searching for server...Please wait");
                address.setEnabled(false);
            }
        });
        byte b[] = new byte[100000];
        // array to retrieve data from server and send to client

        String sizeName[] = new String[2];
        // stores size and name of file as recieved from character streams

        double done=0,length;
        // done is used to count the percentage

        int read=0,i=0;
        // read counts the bytes read (within 4 bytes integer range) in WHILE loop

        // constructing streams
        BufferedReader br=null;
        // to read String and long data via Socket

        PrintWriter pw=null;
        // to write String and long data via Socket

        BufferedInputStream bis=null;
        //to write file contents (byte stream) via Socket

        BufferedOutputStream bos=null;
        //to read byte data via Socket

        FileOutputStream fos=null;
        // to read actual file using byte stream

        Socket s=null;
        // this will serve a local port for a client

        // now allocating memory to objects and starting main logic

        try
        {
            s = new Socket(address.getText(),4000);
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            pw = new PrintWriter(s.getOutputStream());
            StringTokenizer st = new StringTokenizer(br.readLine(),"/");
            status.setText("Connection Established, about to begin download");
            while(st.hasMoreTokens())
                sizeName[i++]=st.nextToken();
            pw.println("Recieved");
            pw.flush();
            length = new Double(sizeName[1]);
            bis = new BufferedInputStream  (s.getInputStream());
            bos = new BufferedOutputStream (s.getOutputStream());
            fos = new FileOutputStream     (location+"\"+sizeName[0]);

            lowerBorder.remove(status);
            remove(lowerBorder);
            add(jpb,BorderLayout.SOUTH);
            repaint();
            revalidate();
            while(true)
            {
                done+=read;
                if(done>=length)
                    break;
                read=bis.read(b);
                ClientSwingWorker csw = new ClientSwingWorker (done,length,read,b,fos,jpb);
                csw.execute();
                while(!(csw.isDone())) {}
            }
            fos.flush();

            address.setEnabled(true);
            recieve.setEnabled(true);
            remove(jpb);
            lowerBorder.add(status);
            add(lowerBorder,BorderLayout.SOUTH);
            status.setText("Recieved 100%");
            repaint();
            revalidate();

            double time        = new Double(br.readLine());
            String speedString = br.readLine();

            bis.close();
            bos.close();
            fos.close();
            pw.close();
            br.close();
            s.close();

            JOptionPane.showMessageDialog(null,"Time taken is "+time+"nSpeed is "+speedString+" MBPS","File Sent (Client)",3);
            status.setText("Enter Server Adress and press 'Recieve File' to Continue");
        }
        catch(Exception e)
        {
            if ( e instanceof ConnectException)
            {
                address.setText("Enter Address as specified by Server");
                status.setText ("Enter Server Adress and press 'Connect and Start' button to Continue");
                address.setEnabled(true);
                recieve.setEnabled(true);
                JOptionPane.showMessageDialog(null,"No Running Server found on specified address [ "+address.getText()+" ]","Server Not Found",0);
                final JTextField temp=address;
                address.addMouseListener(new MouseAdapter()
                {
                    public void mouseClicked(MouseEvent me)
                    {
                        temp.setText("");
                        temp.removeMouseListener(this);
                    }
                });
                return;
            }
            else if (e instanceof FileNotFoundException)
            {
                JOptionPane.showMessageDialog(null,"Failed in saving file,nLocation : "+location+" required administrative rights to save or it was an invalid pathnSelect some other location for downloaded filesnThe Program will now Exit and default location would be reset","Error ["+location+"]",0);
                try
                {
                    FileWriter fw = new FileWriter("c:\sft\log.bin");
                    fw.close();
                }
                catch(IOException ee)
                {
                }
                System.exit(1);
            }
            e.printStackTrace();
        }
    }
    public static void main(String...args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new Client();
            }
        });
    }
}
class ClientSwingWorker extends SwingWorker<void,void>
{
    JProgressBar jpb;
    final double done,size;
    byte b[] = new byte[100000];
    final int read;
    FileOutputStream fos;
    ClientSwingWorker(double done,double size,int read,byte b[],FileOutputStream fos,JProgressBar jpb)
    {
        this.done = done;
        this.size = size;
        this.read = read;
        this.b    = b;
        this.jpb  = jpb ;
        this.fos  = fos;
    }
    protected Void doInBackground() throws Exception
    {
        fos.write(b,0,read);
        return null;
    }

    protected void done()
    {
        final double temp=(done/size)*100;
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                String tString = new Double(temp).toString();
                int index=tString.indexOf(".");
                int breakPoint= (index+3)>tString.length()?tString.length():(index+3);
                tString=tString.substring(0,breakPoint);
                jpb.setString("Recieving : "+tString+" %");
                jpb.setValue((int)temp);
            }
        });
    }
}

Server Side code (Server.java):

import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Server extends JFrame implements ActionListener
{
    JTextField nameField,sizeField,typeField;
    // textfields in front Dialog

    JButton browse,start;
    // browse is to select the file and start is to start the server

    JFileChooser jfc;
    // to select the file from local computer

    JLabel status,address;
    // shows current status of the app

    JPanel lowerBorder;
    // is removed afterwards, so it is declared class-wide

    JProgressBar jpb;
    // progress bar to show file completion

    final String sizeArray[]={"B","KB","MB","GB","TB"};
    // final string array to set the size of file in desired range

    int screenX,screenY,myX,myY;
    // dialog is undecorated, so these coordinates help to move the frame in the screen

    boolean startFlag=false;
    // this flag sets the StartServer button "working"

    double fileSize;
    // stores the size of file in bytes

    String serverAddress="",tempAddress="";
    // string stores the address of the server, determined inside constructor

    private void add(JComponent parent,JComponent component,int gridx, int gridy, int gridwidth, int gridheight,int posInCell,Insets insets)
    {
        parent.add(component, new GridBagConstraints(gridx, gridy,gridwidth, gridheight, 1.0, 1.0, posInCell, GridBagConstraints.NONE, insets, 0,0));
    }
    // GridBagLayout alignment and add function
    void retrieveServerIP(boolean flag) // flag is false when it is executed for first time, else label is updated
    {
        try
        {
            tempAddress = InetAddress.getLocalHost().toString().substring(InetAddress.getLocalHost().toString().lastIndexOf("/")+1);
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(this,"Unable to Retrieve System IP, Restart the Application and Retry","Runtime Error !",0); // EIWQ
            System.exit(0);
        }
        if(!(tempAddress.equals(serverAddress)))
        {
            serverAddress=tempAddress;
            if(flag)
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {
                        address.setText("Type this in client app : "+serverAddress+" ");
                    }
                });
        }
    }

    // starting constructor for basic initializations
    Server(String path)
    {
        this();
        openFile(new File(path));
    }
    Server()
    {
        // Retrieve Server's IP
        retrieveServerIP(false);
        // set Windows Look and Feel for Windows Systems (only on file chooser)
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null,"Using Swing Default Look and Feel, as you a using a NON-WINDOWS System","Changing look and feel",0);
        }

        // Constructos Declarations
        JButton cross,minimize;
        JLabel nameLabel,sizeLabel,typeLabel,title;
        JPanel panel,upperBorder,flowPanel;

        // Memory allocation

        (browse   = new JButton("Browse")).setForeground(Color.BLACK);
        (start    = new JButton("Send File")).setForeground(Color.BLACK);
        (cross    = new JButton("X")).setForeground(new Color(170,111,236));
        (minimize = new JButton("-")).setForeground(new Color(170,111,236));
        cross.setBackground(Color.WHITE);
        minimize.setBackground(Color.WHITE);

        jfc = new JFileChooser();

        jpb = new JProgressBar();
        jpb.setStringPainted(true);
        jpb.setFont(new Font("Times new roman",Font.BOLD,20));
        jpb.setForeground(new Color(170,111,236));
        jpb.setBackground(Color.BLACK);

        nameLabel  = new JLabel("File Name");
        sizeLabel  = new JLabel("File Size");
        typeLabel  = new JLabel("File Type");
        (title      = new JLabel("  Smart File Transfer (Server)")).setForeground(Color.WHITE);
        address    = new JLabel("Type this in client app : "+serverAddress+" ");
        (status     = new JLabel("Select File and Start Server")).setForeground(Color.WHITE);

        panel = new JPanel();
        panel.setBackground(new Color(170,111,236));

        (upperBorder = new JPanel()).setBackground(Color.BLACK);
        (lowerBorder = new JPanel()).setBackground(Color.BLACK);
        (flowPanel    = new JPanel()).setBackground(Color.BLACK);;

        (nameField = new JTextField(30)).setEditable(false);
        (sizeField = new JTextField(20)).setEditable(false);
        (typeField = new JTextField(20)).setEditable(false);

        nameField.setBackground(Color.WHITE);
        sizeField.setBackground(Color.WHITE);
        typeField.setBackground(Color.WHITE);

        // setting Panel and adding components to Panel
        panel.setLayout(new GridBagLayout());
        upperBorder.setLayout(new BorderLayout());
        lowerBorder.setLayout(new FlowLayout(FlowLayout.CENTER));
        lowerBorder.add(status);

        add(panel,nameLabel,0,1,1,1,GridBagConstraints.WEST,new Insets(0,20,0,0));
        add(panel,nameField,1,1,3,1,GridBagConstraints.WEST,new Insets(0,30,0,0));
        add(panel,browse,4,1,1,1,GridBagConstraints.CENTER,new Insets(0,0,0,0));
        add(panel,sizeLabel,0,2,1,1,GridBagConstraints.WEST,new Insets(0,20,0,0));
        add(panel,sizeField,1,2,3,1,GridBagConstraints.WEST,new Insets(0,30,0,0));
        add(panel,typeLabel,0,3,1,1,GridBagConstraints.WEST,new Insets(0,20,0,0));
        add(panel,typeField,1,3,3,1,GridBagConstraints.WEST,new Insets(0,30,0,0));
        add(panel,start,2,4,1,1,GridBagConstraints.CENTER,new Insets(0,0,0,0));
        add(panel,address,2,5,1,1,GridBagConstraints.WEST,new Insets(0,0,0,0));

        setFont(new Font("GreyscaleBasic",Font.BOLD,20),nameLabel,sizeLabel,typeLabel);
        setFont(new Font("Times new roman",Font.PLAIN,14),nameField,sizeField,typeField);
        setFont(new Font("tahoma",Font.BOLD,20),cross,address,minimize);
        setFont(new Font("times new roman",Font.PLAIN,20),start,browse,status,title);

        // add Listeners
        browse.addActionListener(this);
        start.addActionListener(this);
        cross.addActionListener(this);
        minimize.addActionListener(this);

        // set Top Level Container Properties
        flowPanel.add(minimize);
        flowPanel.add(cross);
        upperBorder.add(flowPanel,BorderLayout.EAST);
        upperBorder.add(title); //not centered, towards left
        add(upperBorder,BorderLayout.NORTH);
        add(panel,BorderLayout.CENTER);
        add(lowerBorder,BorderLayout.SOUTH);

        addMouseListener(new MouseAdapter()
        {
            public void mousePressed(MouseEvent me)
            {
                screenX = me.getXOnScreen();
                screenY = me.getYOnScreen();
                myX     = getX();
                myY     = getY();
            }
        });
        addMouseMotionListener(new MouseMotionAdapter()
        {
            public void mouseDragged(MouseEvent me)
            {
                int deltaX = me.getXOnScreen() - screenX;
                int deltaY = me.getYOnScreen() - screenY;
                setLocation(myX + deltaX , myY + deltaY);
            }
        });
        setSize(800,400);
        setResizable(false);
        setLocationRelativeTo(null);
        setUndecorated(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        getRootPane().setBorder(BorderFactory.createLineBorder(new Color(170,111,236),5));
        getRootPane().setDefaultButton(start);
        setVisible(true);
        browse.requestFocus(); // this must exist here (after frame is visible), else will not work
        new Thread(new Runnable()
        {
            public void run()
            {
                while(true)
                {
                    retrieveServerIP(true);
                }
            }
        }).start();
    }
    private void setFont(Font f,JComponent...c)
    {
        for(JComponent C:c)
            C.setFont(f);
    }
    private void openFile(File path)
    {
        File f=path;
        int counter=0;
        fileSize=f.length();
        if(fileSize==0L)
        {
            JOptionPane.showMessageDialog(null,"No Valid file found on specified location","File not found",0);
            return;
        }
        String extension=f.toString().substring(f.toString().lastIndexOf(".")+1,f.toString().length()).toUpperCase();
        long tempSize=(long)fileSize;
        while(tempSize>1000)
        {
            counter++;
            tempSize/=1024;
        }
        if(extension.equals("JAVA") || extension.equals("C")|| extension.equals("CPP")|| extension.equals("CS")|| extension.equals("CSS")|| extension.equals("HTML")|| extension.equals("JS")|| extension.equals("PHP")|| extension.equals("XML")|| extension.equals("VB"))
            extension+=" Source File";
        else if (extension.equals("JPG") || extension.equals("BMP")|| extension.equals("PNG")|| extension.equals("GIF")|| extension.equals("TIFF") || extension.equals("ICO"))
            extension+=" File (Image/Icon)";
        else if (extension.equals("MPG") || extension.equals("MPEG")|| extension.equals("MP4")|| extension.equals("AVI")|| extension.equals("3GP")|| extension.equals("RMVB")|| extension.equals("WMV")|| extension.equals("MKV")|| extension.equals("VOB")|| extension.equals("MOV") || extension.equals("FLV"))
            extension+=" File (Video)";
        else if (extension.equals("MP3") || extension.equals("WMA")|| extension.equals("FLAC")|| extension.equals("AAC")|| extension.equals("AMF")|| extension.equals("AMR")|| extension.equals("M4A")|| extension.equals("M4R")|| extension.equals("OGG")|| extension.equals("MP2")|| extension.equals("WAV"))
            extension+=" File (Audio)";
        else if (extension.equals("EXE") ||extension.equals("CMD") ||extension.equals("BAT") || extension.equals("DMG") ||extension.equals("MSI"))
            extension+=" File (Executable File/Script)";
        else
            extension+=" Document/File";
        nameField.setText(f.toString());
        sizeField.setText(tempSize +" "+sizeArray[counter]);
        typeField.setText(extension);
        startFlag=true;
    }
    public void actionPerformed(ActionEvent ae)
    {
        String s=ae.getActionCommand();
        if(s.equals("Browse"))
        {
            int ret = jfc.showOpenDialog(null);
            if(ret==JFileChooser.APPROVE_OPTION)
                openFile(jfc.getSelectedFile());
            start.requestFocusInWindow();
        }
        else if(s.equals("X"))
            System.exit(0);
        else if(s.equals("-"))
            setState(JFrame.ICONIFIED);
        else if(s.equals("Send File"))
            if(startFlag)
                new Thread(new Runnable()
                {
                    public void run()
                    {
                        startServer();
                    }
                }).start();
            else
                JOptionPane.showMessageDialog(null,"Select a Valid file first ( size > 0B )","Error",0);
    }
    private void startServer()
    {
        start.setEnabled(false);
        browse.setEnabled(false);
        status.setText("Waiting for Client to Connect");

        double startTime,endTime;
        // time variables;

        byte b[] = new byte[100000];
        // array to retrieve data from server and send to client

        double done=0;
        // done is used to count the percentage

        int read=0;
        // read counts the bytes read (within 4 bytes integer range) in WHILE loop

        String data,fileName = nameField.getText().substring(nameField.getText().lastIndexOf("\")+1);
        // data is the data to be sent via BR, stores (filename + length)
        // fileName stores the name of the file

        // constructing streams
        BufferedReader br=null;
        // to read String and long data via Socket

        PrintWriter pw=null;
        // to write String and long data via Socket

        BufferedInputStream bis=null;
        //to write file contents (byte stream) via Socket

        BufferedOutputStream bos=null;
        //to read byte data via Socket

        FileInputStream fis=null;
        // to read actual file using byte stream

        ServerSocket ss=null;
        // this will open a socket on port 4000 on local system

        Socket s=null;
        // this will serve a local port for a client

        // now allocating memory to objects and starting main logic

        data=fileName+"/"+new Double(fileSize);
        try
        {
            ss = new ServerSocket(4000);
            s = ss.accept();
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            pw = new PrintWriter(s.getOutputStream());
        }
        catch(IOException ioe)
        {
            JOptionPane.showMessageDialog(null,ioe.toString(),"error",0);
            System.exit(0);
        }
        pw.println(data);
        pw.flush();
        try
        {
            status.setText("Begining File Transfer");
            if(!(br.readLine().equals("Recieved")))
            {
                JOptionPane.showMessageDialog(null,"Client not Ready or connection was closed","Retry",2);
                status.setText("Faliure");
                System.exit(0);
            }
            bis = new BufferedInputStream(s.getInputStream());
            bos = new BufferedOutputStream(s.getOutputStream());
            fis = new FileInputStream(nameField.getText());
            status.setText("Sending file to "+s);

            lowerBorder.remove(status);
            remove(lowerBorder);
            add(jpb,BorderLayout.SOUTH);
            repaint();
            revalidate();

            startTime=System.currentTimeMillis();
            while((read=fis.read(b))!=-1)
            {
                done+=read;
                ServerSwingWorker ssw = new ServerSwingWorker(done,fileSize,read,b,bos,jpb);
                ssw.execute();
                while(!(ssw.isDone())){}
            }
            bos.flush();
            endTime=System.currentTimeMillis();
            browse.setEnabled(true);
            start.setEnabled(true);
            nameField.setText("");
            sizeField.setText("");
            typeField.setText("");
            remove(jpb);
            lowerBorder.add(status);
            add(lowerBorder,BorderLayout.SOUTH);
            startFlag=false;
            repaint();
            revalidate();
            status.setText("Sent 100 %");
            double time=(endTime-startTime)/1000;
            double speed=(fileSize/time)/1048576;
            String speedString=String.valueOf(speed);
            speedString=((speedString.indexOf(".")+3)<speedString.length()?speedString.substring(0,speedString.indexOf(".")+3):speedString.substring(0));
            pw.println(time);
            pw.flush();
            pw.println(speedString);
            pw.flush();
            JOptionPane.showMessageDialog(null,"Time taken is "+time+"nSpeed is "+speedString+" MBPS","File Sent (Server)",3);
            status.setText("Select File and Start Server");

            // reset for further operation
            status.setText("Select File and Start Server");
            bis.close();
            bos.close();
            fis.close();
            br.close();
            pw.close();
            ss.close();
            s.close();
        }
        catch(IOException ioe)
        {
            JOptionPane.showMessageDialog(null,ioe.toString(),"Error",0);
            System.exit(0);
        }

    }
    public static void main(final String...args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                if( args.length==1 && !(args[0].equals("%1")) )
                    new Server(args[0]);
                else
                    new Server();
            }
        });
    }
}
class ServerSwingWorker extends SwingWorker
{
    JProgressBar jpb;
    final double done,size;
    byte b[] = new byte[100000];
    final int read;
    BufferedOutputStream bos;
    ServerSwingWorker(double done,double size,int read,byte b[],BufferedOutputStream bos,JProgressBar jpb)
    {
        this.done = done;
        this.size = size;
        this.read = read;
        this.b    = b;
        this.jpb  = jpb ;
        this.bos  = bos;
    }
    protected Void doInBackground() throws Exception
    {
        bos.write(b,0,read);
        return null;
    }

    protected void done()
    {
        final double temp=(done/size)*100;
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                String tString = new Double(temp).toString();
                int index=tString.indexOf(".");
                int breakPoint= (index+3)>tString.length()?tString.length():(index+3);
                tString = new Double(temp).toString();
                tString=tString.substring(0,breakPoint);
                jpb.setString("Sending : "+tString+" %");
                jpb.setValue((int)temp);
            }
        });
    }
}

Just let us know if you are not able to understand any method or class used here

© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy