How to implement a custom stream in rust, such as TcpStream

178 Views Asked by At

How to implement a custom stream in rust, such as TcpStream, but not TcpStream. For example, the encrypted stream called MyStream below It can be used by pipelines

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


fn main() {
    let listener = TcpListener::bind("127.0.0.1:4000").unwrap();
    println!("Forward 127.0.0.1:4000 to 127.0.0.1:8000");

    for stream in listener.incoming() {
        if let Ok(client) = stream {
            thread::spawn(move || {
                if let Ok(encrypt_socket) = MyTcpStream::new("127.0.0.1:8000") {
                    println!("connect 127.0.0.1:8000 success");
                    let encrypt_socket2 = encrypt_socket.try_clone().unwrap();
                    let client2 = client.try_clone().unwrap();
                    thread::spawn(move || {
                        let _ = io::copy(&mut encrypt_socket2, &mut client2);
                    });
                    let _ = io::copy(&mut client, &mut encrypt_socket);
                }
            });
        }
    }
}
0

There are 0 best solutions below