Working with Files และ Networking ด้วย Crate ยอดนิยม

Sharing is caring!

การจัดการไฟล์และการสื่อสารผ่านเครือข่ายถือเป็นพื้นฐานที่สำคัญในระบบซอฟต์แวร์ ในบทความนี้เราจะเรียนรู้วิธีทำงานกับระบบไฟล์ และการเชื่อมต่อ HTTP, TCP ผ่าน crate ยอดนิยมใน Rust ได้แก่ std::fs, tokio, reqwest และ std::net

File I/O ด้วย std::fs

Rust มี API สำหรับจัดการไฟล์ผ่าน std::fs ซึ่งสามารถเปิด อ่าน เขียน และลบไฟล์ได้อย่างปลอดภัย

การเขียนไฟล์

use std::fs::File;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let mut file = File::create("hello.txt")?;
    file.write_all(b"Hello, Rust!")?;
    Ok(())
}

การอ่านไฟล์

use std::fs;

fn main() -> std::io::Result<()> {
    let content = fs::read_to_string("hello.txt")?;
    println!("File content: {}", content);
    Ok(())
}

อ่าน/เขียนไฟล์แบบ Async ด้วย tokio::fs

ถ้าคุณใช้ async runtime เช่น tokio คุณสามารถใช้ tokio::fs ในการทำ File I/O แบบไม่บล็อก thread ได้

use tokio::fs;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    fs::write("async.txt", "Hello async Rust!").await?;
    let content = fs::read_to_string("async.txt").await?;
    println!("Async File: {}", content);
    Ok(())
}

Networking พื้นฐานด้วย std::net::TcpListener

Rust สามารถสร้าง TCP server ง่าย ๆ ได้จาก std::net:

use std::net::TcpListener;
use std::io::{Read, Write};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    for stream in listener.incoming() {
        let mut stream = stream.unwrap();
        let mut buffer = [0; 512];
        stream.read(&mut buffer).unwrap();
        stream.write(b"HTTP/1.1 200 OK\r\n\r\nHello").unwrap();
    }
}

Client HTTP ด้วย reqwest

reqwest เป็น crate ยอดนิยมสำหรับการส่ง HTTP request แบบ sync และ async

Async GET Request

use reqwest;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let resp = reqwest::get("https://httpbin.org/get").await?;
    let text = resp.text().await?;
    println!("Response: {}", text);
    Ok(())
}

POST Request พร้อม Body

let client = reqwest::Client::new();
let res = client.post("https://httpbin.org/post")
    .body("rust data")
    .send()
    .await?;

Tips: การจัดการ Error และ Retry

  • ใช้ anyhow หรือ thiserror สำหรับ error ที่อ่านง่าย
  • ใช้ tokio-retry หรือ loop สำหรับ retry connection ที่ล้มเหลว
  • ใส่ timeout เสมอในการเชื่อมต่อกับ HTTP หรือ TCP

บทสรุป

การจัดการไฟล์และการเชื่อมต่อเครือข่ายใน Rust มีเครื่องมือครบถ้วนและปลอดภัยต่อการใช้งานจริง โดยมีทั้ง synchronous และ asynchronous API ให้เลือกใช้ตามความเหมาะสม ซึ่งการใช้ Crate อย่าง std::fs, tokio, reqwest จะช่วยให้คุณพัฒนาแอปพลิเคชันระดับ production ได้ง่ายขึ้น

บทความโดย poolsawat.com – Rust สำหรับงานจริงด้านระบบไฟล์และเครือข่าย

Leave a Reply

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *