Please send me an example of a file transfer socket over TCP

hi, I am currently studying Rust programming.

Among them, I am looking for a part that sends files to the socket during the Toy Project.

Usually, other languages put files in buffers and communicate with the server at 1024 bytes, but Rust is looking for such an example.

I can't find it no matter how hard I try. I would appreciate it if you could tell me a small example source that can transfer files with TcpStream without using other crates.

Here's a simple example.

use std::io::{self, Read, Write};
use std::net::TcpStream;
use std::fs::File;

fn main() -> io::Result<()> {
    let mut file = File::open("myfile.txt")?;
    let mut tcp = TcpStream::connect("127.0.0.1:4321")?;
    
    let mut buf = [0; 4096];
    loop {
        let n = file.read(&mut buf)?;
        
        if n == 0 {
            // reached end of file
            break;
        }
        
        tcp.write_all(&buf[..n])?;
    }
    
    Ok(())
}

Also consider io::copy

thanks. ^^

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.