Skip to content

Instantly share code, notes, and snippets.

@sdressler
Created May 12, 2021 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdressler/1985272a8a9a9f9fe6e0bf364771d971 to your computer and use it in GitHub Desktop.
Save sdressler/1985272a8a9a9f9fe6e0bf364771d971 to your computer and use it in GitHub Desktop.
Simple Rust Proxy - Async Version
use async_std::prelude::*;
use async_std::net::{TcpListener, TcpStream};
use async_std::task::spawn;
use futures::join;
use futures::stream::StreamExt;
#[derive(Debug)]
enum Direction {
Back,
Forth
}
#[async_std::main]
async fn main() {
let server = TcpListener::bind("127.0.0.1:15432").await.unwrap();
server.incoming().for_each_concurrent(None, |client| async move {
println!("New conn...");
let client = client.unwrap();
client.set_nodelay(true).unwrap();
spawn(handle_connection(client));
}).await;
}
async fn handle_connection(mut client: TcpStream) {
let mut upstream = TcpStream::connect("127.0.0.1:5432").await.unwrap();
upstream.set_nodelay(true).unwrap();
let mut client_clone = client.clone();
let mut upstream_clone = upstream.clone();
let t_forth = pipe(&mut client, &mut upstream, Direction::Forth);
let t_back = pipe(&mut upstream_clone, &mut client_clone, Direction::Back);
join!(t_back, t_forth);
}
async fn pipe(input: &mut TcpStream, output: &mut TcpStream, direction: Direction) {
// println!("Direction: {:?}", direction);
let mut buffer = [0u8; 32_768];
loop {
match input.read(&mut buffer).await {
Ok(size) => {
if size == 0 {
output.shutdown(std::net::Shutdown::Both).unwrap();
break;
}
/*
let mut size = size;
if is_forth {
size = cache::processor_forth(size, &mut buffer);
}
*/
if output.write(&buffer[..size]).await.is_ok() {
output.flush().await.unwrap();
}
},
Err(error) => { println!("Error: {:?}", error); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment