实现自己的ftp-server:对LIST命令的响应

时间:2014-11-17 19:21:33

标签: ftp ftp-server

我正在尝试在Java上没有任何库的情况下实现我自己的ftp-server。为了测试我的服务器,我使用FTP客户端FileZilla。问题是我无法通过数据连接发送当前目录中的文件列表(或者换句话说,我无法实现FTP命令LIST)。 我尝试了主动和被动两种模式。

这是FileZilla的输出:

Command:    PASV
Response:   227 Entering Passive Mode (192,168,0,87,125,63)
Command:    LIST
Response:   150 Opening BINARY mode data connection.
// Here I'm trying to send list of files through data connection
Response:   226 Transfer complete.
Error:  Connection timed out
Error:  Failed to retrieve directory listing

这是我对LIST和PASV命令的实现:

public class FTPCommandSocket implements Runnable {

    Socket command_socket;
    Socket data_socket = null;
    FTPDataSocket ftpds = null;
    ServerSocket ss = null;
    // ...
    @Override
    public void run() {
        try {
            // Send response to the client.
            sendResponse("220 WELCOME\n");

            while(from_client_command.read(input_b) != -1)
            {
                String input = new String(input_b);
                String cmd = parseInput(input);
                switch(cmd) {
                    // ... (other commands)
                    case Command.PASV:
                        sendResponse("227 Entering Passive Mode (192,168,0,87,125,63)\n");
                        ss = new ServerSocket(125 * 256 + 63);
                        data_socket = ss.accept();
                        ftpds = new FTPDataSocket(data_socket);
                    break;
                    case Command.LIST:
                        sendResponse("150 Opening BINARY mode data connection.\n");
                        ftpds.sendFilesList(cur_path);
                        Thread.sleep(500);
                        sendResponse("226 Transfer complete.\n");
                    break;
                    //... (other commands)
                    default:
                        sendResponse("502 Command is not implemented.\n");
                }
            }
        } catch (...) {}
    }

    private void sendResponse(String string) throws IOException {
        to_client_command.write(string.getBytes());
        to_client_command.flush();
    }
}

这是数据连接类:

public class FTPDataSocket {
    Socket data_socket;
    OutputStream to_client_data;
    InputStream from_client_data;
    private final byte[] input_b = new byte[15000];

    public FTPDataSocket(Socket s) throws IOException {
        this.data_socket = s;
        from_client_data = data_socket.getInputStream();
        to_client_data = data_socket.getOutputStream();
    }

    public void sendFilesList(String path) throws IOException {
        // Debug version: there are no real files yet.
        sendResponse("-rwxr-xr-x 1 100 100 14757 a.out\r\n");
    }

    private void sendResponse(String string) throws IOException {
        to_client_data.write(string.getBytes());
        to_client_data.flush();
        System.out.print(string);
    }
}

你有什么想法,我做错了吗?

提前谢谢!

1 个答案:

答案 0 :(得分:1)

问题是发送数据后套接字没有关闭。