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

在ftp_server/andy1/upload下會發現多了hello文件,而在終端中則會打印ftp_server/andy1/upload/test文件的內容。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章