FakeFtpServer错误:连接被拒绝(连接被拒绝)

huangapple go评论80阅读模式
英文:

FakeFtpServer error: Connection refused (Connection refused)

问题

以下是你提供的代码的中文翻译:

测试类:FTPConnectionTest

public class FTPConnectionTest {
    /** 模拟 FTP 服务器 */
    private static FakeFtpServer FAKE_FTP_SERVER;
    
    /** 模拟 FTP 服务器地址 */
    private static String ADDRESS = "localhost";
    
    /** 模拟 FTP 服务器用户名 */
    private static String USERNAME = "ftpuser";
    
    /** 模拟 FTP 服务器密码 */
    private static String PASSWORD = "ftppasswd";
    
    /** 模拟 FTP 服务器默认根目录 */
    private static String ROOT;
    
    /** 模拟 FTP 服务器端口 */
    private static int PORT = 0;
    
    /** 测试目录在模拟服务器中 */
    private static String DIRECTORY = "/directory";
    
    /** 测试文件 1 */
    private static String FILE1 = "/Human_satellite.txt";
    
    /** 测试文件 1 内容 */
    private static String FILE1_CONTENT = "Ground control to Major Tom...";
    
    /** 测试文件 2 */
    private static String FILE2 = "/wall-e.txt";
    
    /** 测试文件 2 内容 */
    private static String FILE2_CONTENT = "If lost in space, use fire extinguisher";
    
    /** 测试文件 3 */
    private static String FILE3 = "/buzz_lightyear.txt";
    
    /** 测试文件 3 内容 */
    private static String FILE3_CONTENT = "To infinity, and beyond!";
    
    /**
     * 在运行测试之前设置模拟 FTP 服务器
     */
    @BeforeClass
    public static void setupMock() {
        // 创建模拟服务器
        FAKE_FTP_SERVER = new FakeFtpServer();
        FAKE_FTP_SERVER.setServerControlPort(0);  // 自动找到可用端口
        PORT = FAKE_FTP_SERVER.getServerControlPort();
        FAKE_FTP_SERVER.addUserAccount(new UserAccount(USERNAME, PASSWORD, ROOT));
        
        // 获取资源文件夹的路径,用于运行模拟 FTP
        File mockDir = new File("src/test/resources/ftp/mock");
        ROOT = mockDir.getAbsolutePath();

        // 创建模拟文件
        FileSystem fileSystem = new UnixFakeFileSystem();
        fileSystem.add(new DirectoryEntry(ROOT));
        fileSystem.add(new FileEntry(ROOT + FILE1, FILE1_CONTENT));
        fileSystem.add(new DirectoryEntry(ROOT + DIRECTORY));
        fileSystem.add(new FileEntry(ROOT + DIRECTORY + FILE2, FILE2_CONTENT));
        fileSystem.add(new FileEntry(ROOT + DIRECTORY + FILE3, FILE3_CONTENT));
        FAKE_FTP_SERVER.setFileSystem(fileSystem);

        FAKE_FTP_SERVER.start();
    }
    
    /**
     * 在测试完成后停止模拟 FTP 服务器
     */
    @AfterClass
    public static void stop() {
        FAKE_FTP_SERVER.stop();
    }
    
    /**
     * 测试
     */
    @Test
    public void testFetchNewFiles () {
        // 获取输出路径
        String outputPath = "src/test/resources/ftp/result";
        File output = new File(outputPath);
        outputPath = output.getAbsolutePath();
        
        // 创建连接并获取文件
        FTPConnection conn = new FTPConnection(ADDRESS, PORT, USERNAME, PASSWORD, outputPath);
        conn.fetchNewFiles();
        
        // 检查文件是否已下载
        File file1 = new File(outputPath + FILE1);
        assertTrue(file1.exists());
    }
}

FTP 连接类:FTPConnection

public class FTPConnection {
    
    /** 日志记录器 */
    private Logger logger;
    
    /** 用于连接服务器的 FTP 客户端 */
    private FTPClient client;
    
    /** 服务器地址 */
    private String server;
    
    /** 服务器端口(默认 21) */
    private int port;
    
    /** 用于连接服务器的用户名 */
    private String user;
    
    /** 用于连接服务器的密码 */
    private String password;
    
    /** 下载文件的目标目录 */
    private String output;

    /**
     * 构造函数
     * @param server        FTP 服务器地址
     * @param port          FTP 服务器端口
     * @param user          用于连接服务器的用户名
     * @param password      用于连接服务器的密码
     * @param output        下载文件的目标目录
     */
    public FTPConnection (String server, int port, String user, String password, String output) {
        this.logger = LoggerFactory.getLogger(FTPConnection.class);
        this.server = server;
        this.port = port;
        this.user = user;
        this.password = password;
        this.output = output;
        this.client = new FTPClient();
    }
    
    /**
     * 构造函数
     * @param server        FTP 服务器地址
     * @param user          用于连接服务器的用户名
     * @param password      用于连接服务器的密码
     * @param output        下载文件的目标目录
     */
    public FTPConnection (String server, String user, String password, String output) {
        this(server, 21, user, password, output);
    }

    public void fetchNewFiles() {
        // 连接服务器
        try {
            this.client.connect(server, port);    // 这是失败的那行代码
            this.client.login(user, password);
        } catch (IOException e) {
            logger.error("连接到 FTP 服务器 '" + this.server + "' 时出错:" + e.getMessage());
            e.printStackTrace();
            return;
        }
    }
}

控制台部分(仅摘录):

19:24:31.417 [Thread-1] INFO org.mockftpserver.fake.FakeFtpServer - Starting the server on port 0
19:24:31.419 [Thread-1] INFO org.mockftpserver.fake.FakeFtpServer - Actual server port is 34003
19:24:31.444 [main] ERROR com.my.project.importHandler.FTPConnection - 连接到 FTP 服务器 'localhost' 时出错:Connection refused (Connection refused)
  ***   STACK TRACE   ***
19:24:31.457 [Thread-1] DEBUG org.mockftpserver.fake.FakeFtpServer - Cleaning up server...
19:24:31.457 [Thread-1] INFO org.mockftpserver.fake.FakeFtpServer - Server stopped.
英文:

I have a class that downloads files from FTP servers using the Apache FTP Client, and I want to test it. For doing so, I decided to use the FakeFtpServer class from MockFtpServer, but it always fails with the same error: Connection refused (Connection refused).

My test class:

public class FTPConnectionTest {
/** Mock FTP Server */
private static FakeFtpServer FAKE_FTP_SERVER;
/** Mock FTP Server address */
private static String ADDRESS = "localhost";
/** Mock FTP server user name */
private static String USERNAME = "ftpuser";
/** Mock FTP Server password */
private static String PASSWORD = "ftppasswd";
/** Mock FTP Server default root */
private static String ROOT;
/** Mock FTP Server port */
private static int PORT = 0;
/** Test directory in the mock server */
private static String DIRECTORY = "/directory";
/** Test file 1*/
private static String FILE1 = "/Human_satellite.txt";
/** Content of test file 1 */
private static String FILE1_CONTENT = "Ground control to Major Tom...";
/** Test file 1*/
private static String FILE2 = "/wall-e.txt";
/** Content of test file 1 */
private static String FILE2_CONTENT = "If lost in space, use fire extinguisher";
/** Test file 1*/
private static String FILE3 = "/buzz_lightyear.txt";
/** Content of test file 1 */
private static String FILE3_CONTENT = "To infinity, and beyond !";
/**
* Set up a mock FTP server before running the tests
*/
@BeforeClass
public static void setupMock() {
// Create Mock server
FAKE_FTP_SERVER = new FakeFtpServer();
FAKE_FTP_SERVER.setServerControlPort(0);	// Automatically finds available port
PORT = FAKE_FTP_SERVER.getServerControlPort();
FAKE_FTP_SERVER.addUserAccount(new UserAccount(USERNAME, PASSWORD, ROOT));
// Get the path to the resources folder where to run the mock FTP
File mockDir = new File("src/test/resources/ftp/mock");
ROOT = mockDir.getAbsolutePath();
// Create mock files
FileSystem fileSystem = new UnixFakeFileSystem();
fileSystem.add(new DirectoryEntry(ROOT));
fileSystem.add(new FileEntry(ROOT + FILE1, FILE1_CONTENT));
fileSystem.add(new DirectoryEntry(ROOT + DIRECTORY));
fileSystem.add(new FileEntry(ROOT + DIRECTORY + FILE2, FILE2_CONTENT));
fileSystem.add(new FileEntry(ROOT + DIRECTORY + FILE3, FILE3_CONTENT));
FAKE_FTP_SERVER.setFileSystem(fileSystem);
FAKE_FTP_SERVER.start();
}
/**
* The the mock FTP Server once the tests are done
*/
@AfterClass
public static void stop() {
FAKE_FTP_SERVER.stop();
}
/**
* Test
*/
@Test
public void testFetchNewFiles () {
// Get output path
String outputPath = "src/test/resources/ftp/result";
File output = new File(outputPath);
outputPath = output.getAbsolutePath();
// Create the connection and get the files
FTPConnection conn = new FTPConnection(ADDRESS, PORT, USERNAME, PASSWORD, outputPath);
conn.fetchNewFiles();
// Check that the files have bin downloaded
File file1 = new File(outputPath + FILE1);
assertTrue(file1.exists());
}
}

And here is the part of the FTP class that fails:

public class FTPConnection {
/** Logger */
private Logger logger;
/** The FTP Client used to connect to the server */
private FTPClient client;
/** The address of the server */
private String server;
/** The port of the server (default 21) */
private int port;
/** The user name to use to connect to the server */
private String user;
/** The password to use to connect to the server */
private String password;
/** The directory where to save the downloaded files */
private String output;
/**
* Constructor
* @param server			the address of the FTP server
* @param port				the port of the FTP server
* @param user				the user name to use to connect to the server
* @param password		the password to use to connect to the server
* @param output			the output directory where to download the files
*/
public FTPConnection (String server, int port, String user, String password, String output) {
this.logger = LoggerFactory.getLogger(FTPConnection.class);
this.server = server;
this.port = port;
this.user = user;
this.password = password;
this.output = output;
this.client = new FTPClient();
}
/**
* Constructor
* @param server			the address of the FTP server
* @param user				the user name to use to connect to the server
* @param password		the password to use to connect to the server
* @param output			the output directory where to download the files
*/
public FTPConnection (String server, String user, String password, String output) {
this(server, 21, user, password, output);
}
public void fetchNewFiles() {
// Connect to the server
try {
this.client.connect(server, port);    // That's the line that fails
this.client.login(user, password);
} catch (IOException e) {
logger.error("Error while connecting to FTP server '" + this.server + "': " + e.getMessage());
e.printStackTrace();
return;
}
}
}

And finally an extract of what's going on in the console:

19:24:31.417 [Thread-1] INFO org.mockftpserver.fake.FakeFtpServer - Starting the server on port 0
19:24:31.419 [Thread-1] INFO org.mockftpserver.fake.FakeFtpServer - Actual server port is 34003
19:24:31.444 [main] ERROR com.my.project.importHandler.FTPConnection - Error while connecting to FTP server 'localhost': Connection refused (Connection refused)
***   STACK TRACE   ***
19:24:31.457 [Thread-1] DEBUG org.mockftpserver.fake.FakeFtpServer - Cleaning up server...
19:24:31.457 [Thread-1] INFO org.mockftpserver.fake.FakeFtpServer - Server stopped.

答案1

得分: 1

好的,我找到了:FAKE_FTP_SERVER.setServerControlPort(0); 将服务器端口的值设置为0,而自动选择可用端口只会发生在 FAKE_FTP_SERVER.start(); 期间。我将 PORT = FAKE_FTP_SERVER.getServerControlPort(); 这行代码移动到了 FAKE_FTP_SERVER.start(); 之后,现在它可以正常工作。

英文:

Ok, I found it: FAKE_FTP_SERVER.setServerControlPort(0); sets the value of the server port to 0, and the automatic selection of an available port only happens during FAKE_FTP_SERVER.start();. I moved the line PORT = FAKE_FTP_SERVER.getServerControlPort(); after FAKE_FTP_SERVER.start(); and now it works.

huangapple
  • 本文由 发表于 2020年10月20日 01:41:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64432588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定