风起漂泊 发表于 2015-5-28 12:30:16

FTP客户端之原理与实现


  
  
  


代码



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.*;
import java.net.*;
/**
* This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
* Builder, which is free for non-commercial use. If Jigloo is being used
* commercially (ie, by a corporation, company or business for any purpose
* whatever) then you should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details. Use of Jigloo implies
* acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
* PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
* ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class FTPClient extends javax.swing.JFrame {
    private JSplitPane jSplitPane1;
    private JPanel jPanel1;
    private JLabel jLabel3;
    private JLabel jLabel4;
    private JPanel jPanel4;
    private JPanel jPanel3;
    private JSplitPane jSplitPane2;
    private JPasswordField jPasswordField1;
    private JMenuItem jMenuItem2;
    private JMenuItem jMenuItem1;
    private JPopupMenu jPopupMenu1;
    private JList jList1;
    private JScrollPane jScrollPane2;
    private JTextArea jTextArea1;
    private JScrollPane jScrollPane1;
    private JButton jButton1;
    private JButton jButton2;
    private JTextField jTextField3;
    private JTextField jTextField2;
    private JLabel jLabel2;
    private JTextField jTextField1;
    private JLabel jLabel1;
    private JPanel jPanel2;
    {
      // Set Look & Feel
      try {
            javax.swing.UIManager
                  .setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
      } catch (Exception e) {
            e.printStackTrace();
      }
    }
    /**
   * Auto-generated main method to display this JFrame
   */
    public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                FTPClient inst = new FTPClient();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            }
      });
    }
    public FTPClient() {
      super("MYFTP");
      initGUI();
      uploadThread = null;
      downloadThread = null;
    }
    private void initGUI() {
      try {
            GridLayout thisLayout = new GridLayout(1, 1);
            thisLayout.setHgap(5);
            thisLayout.setVgap(5);
            thisLayout.setColumns(1);
            getContentPane().setLayout(thisLayout);
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            this.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                  thisWindowClosing(evt);
                }
            });
            {
                jSplitPane1 = new JSplitPane();
                getContentPane().add(jSplitPane1);
                jSplitPane1.setPreferredSize(new java.awt.Dimension(792, 344));
                jSplitPane1.setOrientation(JSplitPane.VERTICAL_SPLIT);
                {
                  jPanel1 = new JPanel();
                  GridLayout jPanel1Layout = new GridLayout(1, 1);
                  jPanel1Layout.setHgap(5);
                  jPanel1Layout.setVgap(20);
                  jPanel1Layout.setColumns(1);
                  jPanel1.setLayout(jPanel1Layout);
                  jSplitPane1.add(jPanel1, JSplitPane.RIGHT);
                  {
                        jSplitPane2 = new JSplitPane();
                        jPanel1.add(jSplitPane2);
                        jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
                        {
                            jPanel3 = new JPanel();
                            GridLayout jPanel3Layout = new GridLayout(1, 1);
                            jPanel3Layout.setHgap(5);
                            jPanel3Layout.setVgap(5);
                            jPanel3Layout.setColumns(1);
                            jPanel3.setLayout(jPanel3Layout);
                            jSplitPane2.add(jPanel3, JSplitPane.RIGHT);
                            jPanel3.setPreferredSize(new java.awt.Dimension(
                                    788, 260));
                            {
                              jScrollPane1 = new JScrollPane();
                              jPanel3.add(jScrollPane1);
                              {
                                    jTextArea1 = new JTextArea();
                                    jScrollPane1.setViewportView(jTextArea1);
                              }
                            }
                        }
                        {
                            jPanel4 = new JPanel();
                            GridLayout jPanel4Layout = new GridLayout(1, 2);
                            jPanel4Layout.setHgap(5);
                            jPanel4Layout.setVgap(5);
                            jPanel4Layout.setColumns(2);
                            jPanel4.setLayout(jPanel4Layout);
                            jSplitPane2.add(jPanel4, JSplitPane.LEFT);
                            {
                              jScrollPane2 = new JScrollPane();
                              jPanel4.add(jScrollPane2);
                              {
                                    ListModel jList1Model = new DefaultListModel();
                                    jList1 = new JList();
                                    jScrollPane2.setViewportView(jList1);
                                    jList1.setModel(jList1Model);
                                    {
                                        jPopupMenu1 = new JPopupMenu();
                                        setComponentPopupMenu(jList1,
                                                jPopupMenu1);
                                        {
                                          jMenuItem1 = new JMenuItem();
                                          jPopupMenu1.add(jMenuItem1);
                                          jMenuItem1.setText("\u4e0a\u4f20");
                                          jMenuItem1
                                                    .addActionListener(new ActionListener() {
                                                      public void actionPerformed(
                                                                ActionEvent evt) {
                                                            jMenuItem1ActionPerformed(evt);
                                                      }
                                                    });
                                        }
                                        {
                                          jMenuItem2 = new JMenuItem();
                                          jPopupMenu1.add(jMenuItem2);
                                          jMenuItem2.setText("\u4e0b\u8f7d");
                                          jMenuItem2
                                                    .addActionListener(new ActionListener() {
                                                      public void actionPerformed(
                                                                ActionEvent evt) {
                                                            jMenuItem2ActionPerformed(evt);
                                                      }
                                                    });
                                        }
                                    }
                                    jList1.addMouseListener(new MouseAdapter() {
                                        public void mouseClicked(MouseEvent evt) {
                                          jList1MouseClicked(evt);
                                        }
                                    });
                              }
                            }
                        }
                  }
                }
                {
                  jPanel2 = new JPanel();
                  FlowLayout jPanel2Layout = new FlowLayout();
                  jPanel2Layout.setHgap(10);
                  jPanel2.setLayout(jPanel2Layout);
                  jSplitPane1.add(jPanel2, JSplitPane.LEFT);
                  {
                        jLabel1 = new JLabel();
                        jPanel2.add(jLabel1);
                        jLabel1.setText("\u4e3b\u673a\uff1a");
                        jLabel1
                              .setPreferredSize(new java.awt.Dimension(39, 15));
                  }
                  {
                        jTextField1 = new JTextField();
                        jPanel2.add(jTextField1);
                        jTextField1.setPreferredSize(new java.awt.Dimension(
                              120, 22));
                        jTextField1.setText("ftp.gdut.edu.cn");
                  }
                  {
                        jLabel2 = new JLabel();
                        jPanel2.add(jLabel2);
                        jLabel2.setText("\u7aef\u53e3\uff1a");
                  }
                  {
                        jTextField2 = new JTextField();
                        jPanel2.add(jTextField2);
                        jTextField2.setPreferredSize(new java.awt.Dimension(50,
                              22));
                        jTextField2.setText("21");
                  }
                  {
                        jLabel3 = new JLabel();
                        jPanel2.add(jLabel3);
                        jLabel3.setText("\u7528\u6237\u540d\uff1a");
                  }
                  {
                        jTextField3 = new JTextField();
                        jPanel2.add(jTextField3);
                        jTextField3.setText("anonymous");
                        jTextField3.setPreferredSize(new java.awt.Dimension(
                              120, 22));
                  }
                  {
                        jLabel4 = new JLabel();
                        jPanel2.add(jLabel4);
                        jLabel4.setText("\u5bc6\u7801\uff1a");
                  }
                  {
                        jPasswordField1 = new JPasswordField();
                        jPanel2.add(jPasswordField1);
                        jPasswordField1
                              .setPreferredSize(new java.awt.Dimension(120,
                                        22));
                  }
                  {
                        jButton1 = new JButton();
                        jPanel2.add(jButton1);
                        jButton1.setText("\u8fde\u63a5");
                        jButton1
                              .setPreferredSize(new java.awt.Dimension(50, 22));
                        jButton1.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                              jButton1ActionPerformed(evt);
                            }
                        });
                        jButton1.setEnabled(true);
                  }
                  {
                        jButton2 = new JButton();
                        jPanel2.add(jButton2);
                        jButton2.setText("\u65ad\u5f00");
                        jButton2
                              .setPreferredSize(new java.awt.Dimension(50, 22));
                        jButton2.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                              jButton2ActionPerformed(evt);
                            }
                        });
                        jButton2.setEnabled(false);
                  }
                }
            }
            setSize(800, 600);
      } catch (Exception e) {
            e.printStackTrace();
      }
    }
    /*
   * 连接FTP服务器
   */
    public boolean contFTPServer() {
      String strHost = null;
      String strPort = null;
      String user = null;
      String password = null;
      // 获取主机和端口号
      strHost = jTextField1.getText();
      strPort = jTextField2.getText();
      if (strHost.equals("") || strPort.equals("")) {
            JOptionPane.showMessageDialog(this, "主机或端口号不能为空!");
            return false;
      }
      // 连接
      try {
            sock = new Socket(strHost, Integer
                  .parseInt(strPort));
      } catch (UnknownHostException e) {
            JOptionPane.showMessageDialog(this, "连接失败:未知主机地址!");
            return false;
      } catch (ConnectException e) {
            JOptionPane.showMessageDialog(this, "连接失败:未知端口号!");
            return false;
      } catch (IOException e) {
            e.printStackTrace();
      }
      // 打开输入输出流
      try {
            bfrd = new BufferedReader(new InputStreamReader(sock
                  .getInputStream()));
            bfwt = new BufferedWriter(new OutputStreamWriter(sock
                  .getOutputStream()));
      } catch (IOException e1) {
            e1.printStackTrace();
      }
      // 启动线程接收服务器返回信息
      if(recvServMsg != null) {
            try {
                recvServMsg.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
      }
      recvServMsg = new Thread(new Runnable() {
            public void run() {
                String msg = null;
                DefaultCaret caret = (DefaultCaret) jTextArea1.getCaret();
                caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
                try {
                  while ((msg = bfrd.readLine()) != null) {
                        jTextArea1.append(msg + "\n");
                  }
                } catch (NullPointerException e) {
                } catch (IOException e) {
                  // e.printStackTrace();
                }
            }
      });
      recvServMsg.start();
      // 发送用户名和密码
      user = jTextField3.getText();
      if (user.equals("")) {
            user = "anonymous";
      }
      password = new String(jPasswordField1.getPassword());
      try {
            bfwt.write("USER " + user + "\r\n");
            bfwt.write("PASS " + password + "\r\n");
            bfwt.write("SYST\r\n");
            bfwt.flush();
      } catch (IOException e) {
            e.printStackTrace();
      }
      jButton1.setEnabled(false);
      jButton2.setEnabled(true);
      return true;
    }
    /*
   * 获取临时插口
   */
    public void getTempServSock() {
      try {
            tmpServSock = new ServerSocket();
            tmpServSock.bind(null);
      } catch (IOException e) {
            e.printStackTrace();
      }
      // 将IP地址和端口号转换成FTP规定格式
      strAddrPort = "";
      String strAddr = sock.getLocalAddress().toString();
      int port = tmpServSock.getLocalPort();
      int i, j = 1;
      for (i = 1; i < strAddr.length(); ++i) {
            if (strAddr.charAt(i) == '.') {
                strAddrPort += strAddr.substring(j, i) + ",";
                j = i + 1;
            }
      }
      strAddrPort += strAddr.substring(j, i);
      strAddrPort += "," + (port / 256) + "," + (port % 256);
    }
    /*
   * 显示当前目录
   */
    public void dirFunc() {
      getTempServSock();
      try {
            bfwt.write("PORT " + strAddrPort + "\r\n");
            bfwt.write("LIST\r\n");
            bfwt.flush();
      } catch (IOException e) {
            e.printStackTrace();
      }
      showList();
    }
    /*
   * 进入目录
   */
    public void cdFunc(String path) {
      try {
            bfwt.write("CWD " + path + "\r\n");
            bfwt.flush();
      } catch (IOException e) {
            e.printStackTrace();
      }
    }
    /*
   * 显示列表
   */
    public void showList() {
      try {
            DefaultListModel listModel = (DefaultListModel) jList1.getModel();
            Socket tmpSock = tmpServSock.accept();
            BufferedReader tmpBfrd = new BufferedReader(new InputStreamReader(
                  tmpSock.getInputStream()));
            String line;
            listModel.removeAllElements();
            listModel.addElement(pdirInfo);
            while ((line = tmpBfrd.readLine()) != null) {
                listModel.addElement(line);
            }
            tmpBfrd.close();
            tmpSock.close();
      } catch (IOException e) {
            e.printStackTrace();
      }
    }
    /*
   * 断开连接
   */
    public void closeFunc() {
      if (sock == null)
            return;
      if ((uploadThread != null && uploadThread.isAlive())
                || (downloadThread != null && downloadThread.isAlive())) {
            JOptionPane.showMessageDialog(this, "正在上传或下载...", "注意",
                  JOptionPane.WARNING_MESSAGE);
            return;
      }
      try {
            if (uploadThread != null) {
                uploadThread.join();
            }
            if (downloadThread != null) {
                downloadThread.join();
            }
      } catch (InterruptedException e) {
            e.printStackTrace();
      }
      try {
            bfwt.write("QUIT\r\n");
            bfwt.flush();
      } catch (IOException e1) {
            e1.printStackTrace();
      }
      closeScoket();
      jButton1.setEnabled(true);
      jButton2.setEnabled(false);
    }
    /*
   * 连接按键事件处理
   */
    private void jButton1ActionPerformed(ActionEvent evt) {
      if (contFTPServer()) {
            dirFunc();
      }
    }
    /*
   * 断开按钮事件处理
   */
    private void jButton2ActionPerformed(ActionEvent evt) {
      closeFunc();
    }
    /*
   * jList鼠标事件处理
   */
    private void jList1MouseClicked(MouseEvent evt) {
      if (sock == null)
            return;
      // 左键双击
      if ((evt.getButton() == MouseEvent.BUTTON1)
                && (evt.getClickCount() == 2)) {
            int i;
            String info = (String) jList1.getSelectedValue();
            if(info == null)
                return;
            if (info.equals(pdirInfo)) {
                cdFunc("..");
                dirFunc();
            } else if (info.charAt(0) == 'd') {
                boolean space = true;
                int cnt = 0;
                for(i = 0; i < info.length(); ++i) {
                  if(info.charAt(i) != ' ') {
                        if(space) {
                            ++cnt;
                            space = false;
                            if(cnt >= 9) {
                              break;
                            }
                        }
                  }
                  else
                        space = true;
                }
                cdFunc(info.substring(i, info.length()));
                dirFunc();
            }
      }
    }
    /*
   * 上传文件
   */
    public void uploadFunc() {
      int returnVal;
      JFileChooser chooser = new JFileChooser();
      returnVal = chooser.showOpenDialog(this);
      getTempServSock();
      if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                bfwt.write("PORT " + strAddrPort + "\r\n");
                bfwt.write("STOR " + chooser.getSelectedFile().getName()
                        + "\r\n");
                bfwt.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                int cnt;
                final int SIZE = 1024;
                byte[] rdbt = new byte;
                Socket tmpSock = tmpServSock.accept();
                BufferedOutputStream tmpBfos = new BufferedOutputStream(tmpSock
                        .getOutputStream());
                FileInputStream fis = new FileInputStream(chooser
                        .getSelectedFile().getAbsolutePath());
                while ((cnt = fis.read(rdbt, 0, SIZE)) > 0) {
                  tmpBfos.write(rdbt, 0, cnt);
                }
                tmpBfos.close();
                tmpSock.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
      }
    }
    /*
   * 下载文件
   */
    public void downloadFunc(String file) {
      JFileChooser chooser = new JFileChooser();
      int returnVal;
      chooser.setDialogType(JFileChooser.SAVE_DIALOG);
      returnVal = chooser.showSaveDialog(this);
      if (returnVal == JFileChooser.APPROVE_OPTION) {
            getTempServSock();
            try {
                bfwt.write("TYPE I\r\n");
                bfwt.write("PORT " + strAddrPort + "\r\n");
                bfwt.write("RETR " + file + "\r\n");
                bfwt.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                int cnt;
                final int SIZE = 1024;
                byte[] rdbt = new byte;
                Socket tmpSock = tmpServSock.accept();
                BufferedInputStream tmpBfis = new BufferedInputStream(tmpSock
                        .getInputStream());
                FileOutputStream tmpfos = new FileOutputStream(chooser
                        .getSelectedFile().getAbsolutePath());
                while ((cnt = tmpBfis.read(rdbt, 0, SIZE)) > 0) {
                  tmpfos.write(rdbt, 0, cnt);
                }
                tmpfos.close();
                tmpBfis.close();
                tmpSock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
      }
    }
    /**
   * Auto-generated method for setting the popup menu for a component
   */
    private void setComponentPopupMenu(final java.awt.Component parent,
            final javax.swing.JPopupMenu menu) {
      parent.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent e) {
                if (e.isPopupTrigger())
                  menu.show(parent, e.getX(), e.getY());
            }
            public void mouseReleased(java.awt.event.MouseEvent e) {
                if (e.isPopupTrigger())
                  menu.show(parent, e.getX(), e.getY());
            }
      });
    }
    /*
   * 上传菜单事件处理
   */
    private void jMenuItem1ActionPerformed(ActionEvent evt) {
      if ((sock != null) && (uploadThread == null || !uploadThread.isAlive())) {
            if (uploadThread != null) {
                try {
                  uploadThread.join();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
            }
            // 创建线程上传文件
            uploadThread = new Thread(new Runnable() {
                public void run() {
                  uploadFunc();
                }
            });
            uploadThread.start();
      }
    }
    /*
   * 下载菜单事件处理
   */
    private void jMenuItem2ActionPerformed(ActionEvent evt) {
      if ((sock != null)
                && (downloadThread == null || !downloadThread.isAlive())) {
            if (downloadThread != null) {
                try {
                  downloadThread.join();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
            }
            // 创建下载文件线程
            downloadThread = new Thread(new Runnable() {
                public void run() {
                  int i;
                  String strFile = (String) jList1.getSelectedValue();
                  if (strFile != null && strFile.charAt(0) == '-') {
                        boolean space = true;
                        int cnt = 0;
                        for(i = 0; i < strFile.length(); ++i) {
                            if(strFile.charAt(i) != ' ') {
                              if(space) {
                                    ++cnt;
                                    space = false;
                                    if(cnt >= 9) {
                                        break;
                                    }
                              }
                            }
                            else
                              space = true;
                        }
                        downloadFunc(strFile.substring(i, strFile.length()));
                  }
                }
            });
            downloadThread.start();
      }
    }
    /*
   * 关闭Socket和流
   */
    private void closeScoket() {
      try {
            if (bfrd != null)
                bfrd.close();
            if (bfwt != null)
                bfwt.close();
            if (sock != null)
                sock.close();
            bfrd = null;
            bfwt = null;
            sock = null;
      } catch (IOException e) {
            e.printStackTrace();
      }
    }
    /*
   * 关闭客户端
   */
    private void thisWindowClosing(WindowEvent evt) {
      System.exit(0);
    }
    private Socket sock;
    private BufferedReader bfrd;
    private BufferedWriter bfwt;
    private ServerSocket tmpServSock;
    private String strAddrPort;
    private Thread recvServMsg;
    private Thread downloadThread;
    private Thread uploadThread;
    private final String pdirInfo = ">> 返回上层目录...";
}

  
  
  
  
  
  
页: [1]
查看完整版本: FTP客户端之原理与实现