天天看點

016 Rust網絡程式設計,FTP示例

Github位址

對應源碼:https://github.com/anonymousGiga

說明

本示例使用Rust編寫一個FTP的用戶端,在用戶端中進行下載下傳和上傳的示範。

用戶端

  • 在Cargo.toml檔案中添加:
[dependencies]
ftp = "3.0.1"      
  • 編寫src/main.rs如下:
use std::str;
use std::io::Cursor;
use ftp::FtpStream;

fn main() {
    let mut ftp_stream = FtpStream::connect("127.0.0.1:21").unwrap();
    let _ = ftp_stream.login("andy1", "1").unwrap();

    println!("Current directory: {}", ftp_stream.pwd().unwrap());

    let _ = ftp_stream.cwd("upload").unwrap();

    let remote_file = ftp_stream.simple_retr("./test").unwrap();
    println!("Read file with contents\n{}\n", str::from_utf8(&remote_file.into_inner()).unwrap());

    let mut reader = Cursor::new("Hello from the Rust \"ftp\" crate!".as_bytes());
    let _ = ftp_stream.put("hello", &mut reader);
    println!("Successfully wrote hello");

    let _ = ftp_stream.quit();
}      

測試

按照上一節《015 Rust網絡程式設計,FTP介紹》中搭建ftp server,并且建立使用者andy1,同時在ftp_server/andy1目錄下建立upload檔案夾,在檔案夾放置一個test檔案。

在目前工程目錄下放置一個hello檔案。

cargo run      

繼續閱讀