javaandroidftpftp-client

Java FTPClient: Getting "Connection reset by peer" when calling getReply()


I was recently trying to connect to a FTP server via a mobile application. I'm able to connect to my server and check if it's connected (which it is). Next thing is to login with a username and password following with a passive mode setup. Last thing I did was get the reply code from the server, but when my application is running, my screens goes black. When I reopen my application it says "recv failed: ECONNREST (Connection reset by peer)" as the error message I output. Here is my code:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    ftpClient = new FTPClient();
    textView = (TextView)findViewById(R.id.textView_id);
    textView2 = (TextView)findViewById(R.id.textView2_id);
    textView3 = (TextView)findViewById(R.id.textView3_id);
    textView4 = (TextView)findViewById(R.id.textView4_id);
    textView5 = (TextView)findViewById(R.id.textView5_id);

    try{
        ftpClient.connect(ip, port);
        boolean connectSucces = ftpClient.isConnected();
        ftpClient.login(userName,passWord);
        ftpClient.enterLocalPassiveMode();
        ftpClient.getReply();
        int connectionMode = ftpClient.getDataConnectionMode();
        if(connectionMode == ftpClient.PASSIVE_LOCAL_DATA_CONNECTION_MODE)    {
            textView.setText("Connected: " + connectSucces + " ConnectionMode: " + connectionMode);
        }
    }catch(Exception e){
        textView.setText(e.getMessage());
    }
}

Am I missing something?


Solution

  • I believe it's the call to getReply() that deadlocks your code.

    You didn't send any command to which the server should reply, so the client waits for the response until it or the server times out.

    The latter happened probably, that's why the connection was closed/reset by the server.

    You generally do not call getReply() yourself. In most cases it's called internally by the FTPClient for you:

    Only use this method if you are implementing your own FTP client or if you need to fetch a secondary response from the FTP server.


    While I have no experience with Android development, from the symptoms and your code, I assume you connect to the FTP server from a GUI thread, what is rather a bad practice. That would explain why the screen goes blank while you wait.