设为首页 收藏本站
查看: 701|回复: 0

FTP客户端之原理与实现

[复制链接]

尚未签到

发表于 2015-5-28 12:30:16 | 显示全部楼层 |阅读模式
DSC0000.jpg
  
  
  


DSC0001.gif DSC0002.gif 代码



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[SIZE];
                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[SIZE];
                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 = ">> 返回上层目录...";
}

  
  
  
  
  
  
DSC0003.jpg

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-71505-1-1.html 上篇帖子: 在Windows上使用telnet和ftp连接Minix的步骤 下篇帖子: 关于c#连接ftp进行上传下载
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表