2015-10-18 117 views
0
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import java.net.Socket; 

public class FTPClient { 
protected Socket sk; 
protected BufferedReader in; 
protected BufferedWriter out; 

public static void main (String [] args){ 
    FTPClient fc1 = new FTPClient("sitename.org",21); 
    fc1.Login("user", "password!"); 
} 

FTPClient(String server, int port){ 
    try{ 
     this.sk = new Socket(server,port); 
     this.in = new BufferedReader(new InputStreamReader(sk.getInputStream())); 
     this.out = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())); 

     String response = in.readLine(); 
     System.out.println(response); 
    } 
    catch(Exception e){ 
     System.out.println(e); 
    } 

} 

public boolean Login(String user, String pass){ 
    boolean success = false; 
    try{ 
     sendOut("USER " + user); 
     sendOut("PASS " + pass); 
     success = true; 
     System.out.println("Waiting for response"); 
     String response = in.readLine(); 
     System.out.println(response); 

    } 
    catch(Exception e){ 
     System.out.println("Login Failure"); 
     success = false; 
    } 

    return(success); 
} 

public void sendOut(String command) throws Exception{ 
    if (sk == null){ 
     throw new Exception("Client is not connected!"); 
    } 

    try{ 
     out.write(command + "\r\n"); 
     out.flush(); 
    } 
    catch(Exception e){ 
     System.out.println(e); 
    } 
} 

}在Java中與java.net - 連接創建FTP客戶端被拒絕:連接

你好,我寫了這個代碼,客戶端嘗試使用FTP連接連接和登錄到服務器。但是,我不斷收到此錯誤消息, java.net.ConnectException:連接被拒絕:連接 有人可以幫我嗎?

+1

ftp是端口21 ssh是22 – user993553

+0

我看到我會再試一次。 – Dan

+0

現在它告訴我「連接被拒絕:連接」 – Dan

回答

1

您嘗試連接到SSH服務器,因此您會收到意外的回覆。默認的FTP端口是21.

0

好吧......我學校的服務器沒有FTP設置並在端口21上打開。所以,我在端口21上啓動了我的服務器上的FTP,現在它已正確連接。感謝您幫助我解決拍攝問題。

經驗教訓:FTP通常位於端口21上。但是,如果存在連接問題,應通過登錄並使用「sudo netstat netstat -lntu」命令檢查服務器是否正在偵聽端口21。如果FTP連接不上,可以運行「sudo apt-get install vsftpd」來安裝。

謝謝大家幫我解決問題的答案。