Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Simple Ftp server for uploading and downloading file

  1. #1
    Junior Member
    Join Date
    Jan 2014
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Simple Ftp server for uploading and downloading file

    Hyee frnds,

    I want to create a simple ftp server which can upload and download a single file.
    i found code from google search but its showing error : connection refused .
    here is my server code n client code.
    help me its urgent. i m new with this..thanx..

    //server code
    [highlight = java]
    import java.io.*;
    import java.net.*;
     
    public class FtpServer
    {
         public static void main(String [] args)
         {
              int i=1;
     
    System.out.println("**************************");
              System.out.println("*****   FTP SERVER *******");
     
    System.out.println("*********************************************");
              System.out.println("Server Started...");
              System.out.println("Waiting for connections...");
              System.out.println(" ");
              try
              {
     
                   ServerSocket s = new ServerSocket(100);
                   for(;;)
                   {
                        Socket incoming = s.accept();
                        System.out.println("New Client Connected with id " + i +" from "+incoming.getInetAddress().getHostName()+"..." );
                        Thread t = new ThreadedServer(incoming,i);
                        i++;
                        t.start();
                   }
     
              }
              catch(Exception e)
              {
                   System.out.println("Error: " + e);
              }
         }
     
    }
     
    class ThreadedServer extends Thread
    {
         int n;
         String c,fn,fc;
         String filenm;
         Socket incoming;
         int counter;
         String dirn="c://FTP SERVER DIRECTORY";
         public ThreadedServer(Socket i,int c)
         {
              incoming=i;
              counter=c;
         }
     
         public void run()
         {
              try
              {
     
                   BufferedReader in =new BufferedReader(new InputStreamReader(incoming.getInputStream()));
                   PrintWriter out = new PrintWriter(incoming.getOutputStream(), true);
                   OutputStream output=incoming.getOutputStream();
                   fn=in.readLine();
                   c=fn.substring(0,1);
     
                   if(c.equals("#"))
                   {
                   n=fn.lastIndexOf("#");
                   filenm=fn.substring(1,n);
                   FileInputStream fis=null;
                   boolean filexists=true;
                   System.out.println("Request to download file"+filenm+" recieved from "+incoming.getInetAddress().getHostName()+"...");
                   try
                     {
                      fis=new FileInputStream(filenm);
                     }
                   catch(FileNotFoundException exc)
                     {
                      filexists=false;
                      System.out.println("FileNotFoundException:"+exc.getMessage());
                     }
                    if(filexists)
                    {
                     sendBytes(fis, output) ;
    		 fis.close();
                    }
                   }
                  else
                     {
                      try
                      {
                      boolean done=true;
                      System.out.println(" Request to upload file " +fn+"recieved from "+incoming.getInetAddress().getHostName()+"...");
     
                      File dir=new File(dirn);
                      if(!dir.exists())
                      {
                       dir.mkdir();
                      }
                      else
                      {}
                        File f=new File(dir,fn);
                        FileOutputStream fos=new FileOutputStream(f);
                        DataOutputStream dops=new DataOutputStream(fos);
     
                       while(done)
                       {
                        fc=in.readLine();
                        if(fc==null)
                        {
                         done=false;
                        }
                        else
                        {
                         dops.writeChars(fc);
                        // System.out.println(fc);
     
                        }
                     }
                     fos.close();
                     }
                     catch(Exception ecc)
                     {
                      System.out.println(ecc.getMessage());
                     }
                    }
                   incoming.close();
              }
              catch(Exception e)
              {
                   System.out.println("Error: " + e);
              }
         }
         private static void sendBytes(FileInputStream f,OutputStream op)
    throws Exception
         {
          byte[] buffer=new byte[1024];
          int bytes=0;
     
          while((bytes=f.read(buffer))!=-1)
          {
           op.write(buffer,0,bytes);
          }
         }
    }
     
     
     
    //client code
     
     
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FtpClient extends JFrame implements ActionListener {
    	private static final long serialVersionUID = 1L;
     String fn,filenm;
     String fc;
     String dirn="c://FTP CLIENT DIRECTORY";
     JPanel pnl;
     JLabel lbltle,lblud;
     Font fnt;
     JTextField txtfn;
     JButton btnu,btnd;
     Socket s;
     InputStreamReader in;
     OutputStream out;
     BufferedReader br;
     PrintWriter pw;
     public FtpClient()
     {
      super("FTP CLIENT");
     
      pnl=new JPanel(null);
     
      fnt=new Font("Times New Roman",Font.BOLD,25);
     
      lbltle=new JLabel("FTP CLIENT");
      lbltle.setFont(fnt);
      lbltle.setBounds(225,35,200,30);
      pnl.add(lbltle);
     
      lblud=new JLabel("ENTER  FILE-NAME :");
      lblud.setBounds(100,100,150,35);
      pnl.add(lblud);
     
      txtfn=new JTextField();
      txtfn.setBounds(300,100,200,25);
      pnl.add(txtfn);
     
      btnu=new JButton("UPLOAD");
      btnu.setBounds(150,200,120,35);
      pnl.add(btnu);
     
     
      btnd=new JButton("DOWNLOAD");
      btnd.setBounds(320,200,120,35);
     
      pnl.add(btnd);
     
      btnu.addActionListener(this);
      btnd.addActionListener(this);
      getContentPane().add(pnl);
     
      try
      {
      s=new Socket("localhost",100);
      br=new BufferedReader(new InputStreamReader(s.getInputStream()));
      pw=new PrintWriter(s.getOutputStream(),true);
      out=s.getOutputStream();
      }
      catch(Exception e)
      {
       System.out.println("ExCEPTION :"+e.getMessage());
      }
     }
     public void actionPerformed(ActionEvent e)
     {
      if(e.getSource()==btnu)
      {
       try
       {
       filenm=txtfn.getText();
       pw.println(filenm);
       FileInputStream  fis=new FileInputStream(filenm);
       byte[] buffer=new byte[1024];
       int bytes=0;
     
       while((bytes=fis.read(buffer))!=-1)
       {
        out.write(buffer,0,bytes);
       }
       fis.close();
      }
      catch(Exception exx)
      {
       System.out.println(exx.getMessage());
      }
      }
     
      if(e.getSource()==btnd)
      {
       try
       {
       File dir=new File(dirn);
       if(!dir.exists())
       {
        dir.mkdir();
       }
       else{}
       boolean done=true;
       filenm=txtfn.getText();
       fn=new String("#"+filenm+"#");
       //System.out.println(filenm);
       pw.println(fn);
       File f=new File(dir,filenm);
       FileOutputStream fos=new FileOutputStream(f);
       DataOutputStream dops=new DataOutputStream(fos);
       while(done)
       {
         fc=br.readLine();
         if(fc==null)
         {
         done=false;
         }
        else
            {
              dops.writeChars(fc);
           //  System.out.println(fc);
     
            }
        }
       fos.close();
      }
     
      catch(Exception exx)
      {}
     
      }
     }
     public static void main(String args[])
     {
      FtpClient ftpc=new FtpClient();
      ftpc.setSize(600,300);
      ftpc.setVisible(true);
     }
    }
    [/highlight]


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,195
    Thanks
    49
    Thanked 2,172 Times in 2,145 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.

    Also please copy the full text of the error messages and paste it here.

    One problem with the code is the empty catch blocks. Make sure all catch blocks call the printStackTrace() method so there are messages printed for any errors.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    eku (January 25th, 2014)

  4. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,855
    My Mood
    Mellow
    Thanks
    178
    Thanked 631 Times in 618 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    Welcome to the forum! Please read this topic to learn how to post code in code or highlight tags and other useful info for newcomers, including a few "house rules" that you'd try to follow when visiting someplace new.

  5. #4
    Junior Member
    Join Date
    Jan 2014
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    error msg is
    ExCEPTION :Connection refused: connect

  6. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,195
    Thanks
    49
    Thanked 2,172 Times in 2,145 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    Quote Originally Posted by eku View Post
    error msg is
    ExCEPTION :Connection refused: connect
    Add the call to printStackTrace() to get the full text of the error messsage showing where the error happens.

    Please edit the post and fix the code tags to format the code.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #6
    Junior Member
    Join Date
    Jan 2014
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    Thanx..
    now code is working.
    But i m not able to upload file.
    Can you plz tell me from where to upload file.
    means i created a file on desktop with .txt format and trying to upload it but it shows a error
    eku.txt (The system cannot find the file specified)

  8. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,195
    Thanks
    49
    Thanked 2,172 Times in 2,145 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    Please copy and post the full text of the console with the command line and the error message .

    On windows To copy the contents of the command prompt window:
    Click on Icon in upper left corner
    Select Edit
    Select 'Select All' - The selection will show
    Click in upper left again
    Select Edit and click 'Copy'

    Paste here.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #8
    Junior Member
    Join Date
    Jan 2014
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation. All rights reserved.

    C:\Users\Ekta>cd desktop

    C:\Users\Ekta\Desktop>dir
    Volume in drive C has no label.
    Volume Serial Number is 78A1-F93B

    Directory of C:\Users\Ekta\Desktop

    25-01-2014 19:18 <DIR> .
    25-01-2014 19:18 <DIR> ..
    24-01-2014 20:35 899,856 1302.1338.pdf
    25-01-2014 20:12 <DIR> check
    06-04-2013 20:09 943 COED11.lnk
    27-12-2013 11:07 638 eclipse.exe - Shortcut (2).lnk
    24-01-2014 20:35 6,986 FileServer(1).java
    24-01-2014 20:40 6,971 FileServer.java
    25-01-2014 14:02 5,795 FileUpload.java
    25-01-2014 01:23 49,971 FTP Server and FTP Client (Complete Project)
    - Networking Source Code in Java.htm
    25-01-2014 01:23 <DIR> FTP Server and FTP Client (Complete Project)
    - Networking Source Code in Java_files
    27-09-2013 10:07 2,056 Google App Engine Launcher.lnk
    06-12-2013 11:18 2,609 Google Chrome.lnk
    25-01-2014 01:20 80,698 Java FTP example - Change working directory.
    htm
    25-01-2014 01:20 <DIR> Java FTP example - Change working directory_
    files
    25-01-2014 01:22 152,351 Java Minor Project FTP Server and FTP Clien
    t with Full Source Code and Instructions - _ FaaDoOEngineers.com.htm
    25-01-2014 01:22 <DIR> Java Minor Project FTP Server and FTP Clien
    t with Full Source Code and Instructions - _ FaaDoOEngineers.com_files
    26-12-2013 21:13 <DIR> lab
    16-01-2014 23:23 <DIR> New folder
    07-01-2014 19:01 203,144 new2.htm
    07-01-2014 19:01 <DIR> new2_files
    08-01-2014 11:30 33,728 Programming an HTTP Web Server with Java.htm
    l
    08-01-2014 11:30 <DIR> Programming an HTTP Web Server with Java_fil
    es
    06-10-2013 19:20 589 WampServer.lnk
    14 File(s) 1,446,335 bytes
    10 Dir(s) 40,391,368,704 bytes free

    C:\Users\Ekta\Desktop>cd check

    C:\Users\Ekta\Desktop\check>dir
    Volume in drive C has no label.
    Volume Serial Number is 78A1-F93B

    Directory of C:\Users\Ekta\Desktop\check

    25-01-2014 20:12 <DIR> .
    25-01-2014 20:12 <DIR> ..
    25-01-2014 20:12 4,253 FtpClient.class
    25-01-2014 20:09 2,791 FtpClient.java
    25-01-2014 20:12 2,791 FtpServer.java
    25-01-2014 19:19 2,810 new 3.txt
    4 File(s) 12,645 bytes
    2 Dir(s) 40,391,368,704 bytes free

    C:\Users\Ekta\Desktop\check>javac FtpClient.java

    C:\Users\Ekta\Desktop\check>java FtpClient
    eku.txt (The system cannot find the file specified)

    --- Update ---

    error is :
    eku.txt (The system cannot find the file specified)

    i had copied the copy of command line also.
    plz have a look.
    thanx

  10. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,195
    Thanks
    49
    Thanked 2,172 Times in 2,145 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    eku.txt (The system cannot find the file specified)
    The error message does NOT show the source code line number where the exception happens. Be sure to have a call to the printStackTrace() method in ALL catch blocks so the full text of the error message is shown.

    Where is the eku.txt file located?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #10
    Junior Member
    Join Date
    Jan 2014
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    I created eku.txt file on desktop.

    after calling printStackTrace() method in all catch.
    command line output is :


    Directory of C:\Users\Ekta\Desktop\check

    25-01-2014 20:12 <DIR> .
    25-01-2014 20:12 <DIR> ..
    25-01-2014 20:14 4,253 FtpClient.class
    25-01-2014 20:09 2,791 FtpClient.java
    25-01-2014 20:55 4,213 FtpServer.java
    25-01-2014 19:19 2,810 new 3.txt
    4 File(s) 14,067 bytes
    2 Dir(s) 40,394,682,368 bytes free

    C:\Users\Ekta\Desktop\check>javac FtpServer.java

    C:\Users\Ekta\Desktop\check>java FtpServer
    **************************
    ***** FTP SERVER *******
    *********************************************
    Server Started...
    Waiting for connections...

    java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(Unkno wn Source)
    at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
    at java.net.PlainSocketImpl.bind(Unknown Source)
    at java.net.ServerSocket.bind(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at FtpServer.main(FtpServer.java:20)

    C:\Users\Ekta\Desktop\check>javac FtpClient.java

    C:\Users\Ekta\Desktop\check>java FtpClient
    eku.txt (The system cannot find the file specified)

  12. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,195
    Thanks
    49
    Thanked 2,172 Times in 2,145 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    C:\Users\Ekta\Desktop\check>java FtpClient
    eku.txt (The system cannot find the file specified)
    You missed a call to printStackTrace() for the above error.

    I created eku.txt file on desktop.
    Is eku.txt located where the program is looking for it?
    For example if eku.txt is in the desktop folder and the program is looking in the check folder, the program will not find it.
    If you don't understand my answer, don't ignore it, ask a question.

  13. The Following User Says Thank You to Norm For This Useful Post:

    eku (January 25th, 2014)

  14. #12
    Junior Member
    Join Date
    Jan 2014
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Simple Ftp server for uploading and downloading file

    Thanks everyone for your help..
    location was the problem now its solved..

Similar Threads

  1. Replies: 1
    Last Post: June 20th, 2013, 12:30 PM
  2. Uploading File to server ( Apache.commons.net)
    By quirell in forum Java Networking
    Replies: 5
    Last Post: November 11th, 2012, 10:06 PM
  3. multiple file uploading and downloading
    By priti in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 27th, 2012, 11:34 AM
  4. simple ftp server and ftp client
    By simontkk2005 in forum Java Networking
    Replies: 4
    Last Post: January 26th, 2011, 09:29 AM
  5. [SOLVED] Problem trying to retrieve a file from ftp server
    By alexdd1987 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: December 16th, 2010, 05:27 PM