0

我正在尝试在没有任何 Java 库的情况下实现我自己的 ftp 服务器。为了测试我的服务器,我使用 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);
    }
}

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

先感谢您!

4

1 回答 1

2

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

于 2014-11-24T13:03:15.050 回答