Skip to content

Instantly share code, notes, and snippets.

@eirikb eirikb/listener.rs
Last active Sep 18, 2019

Embed
What would you like to do?
use async_std::io;
use async_std::net::{TcpListener, TcpStream};
use async_std::prelude::*;
use async_std::task;
use futures::{AsyncReadExt, future};
async fn in_to_out(incoming: TcpStream, outgoing: TcpStream) {
let (incoming_reader, incoming_writer) = &mut (&incoming, &incoming);
let (outgoing_reader, outgoing_writer) = &mut (&outgoing, &outgoing);
let a = incoming_reader.copy_into(outgoing_writer);
let b = outgoing_reader.copy_into(incoming_writer);
future::select(a, b).await;
}
async fn setup_in_to_out(from: &str, to: &str) -> io::Result<()> {
let listener = TcpListener::bind(from).await?;
let mut incoming = listener.incoming();
while let Some(incoming) = incoming.next().await {
let incoming = incoming?;
let outgoing = TcpStream::connect(to).await?;
task::spawn(async {
in_to_out(incoming, outgoing).await;
});
}
Ok(())
}
fn main() {
task::block_on(async {
futures::join!(
setup_in_to_out("127.0.0.1:8080", "127.0.0.1:3333"),
setup_in_to_out("127.0.0.1:8081", "127.0.0.1:3333")
)
});
}
use async_std::io;
use async_std::net::{TcpListener, TcpStream};
use async_std::prelude::*;
use async_std::task;
use futures::{AsyncReadExt, future};
async fn handle(incoming: TcpStream, outgoing: TcpStream) {
let (incoming_reader, incoming_writer) = &mut (&incoming, &incoming);
let (outgoing_reader, outgoing_writer) = &mut (&outgoing, &outgoing);
let a = incoming_reader.copy_into(outgoing_writer);
let b = outgoing_reader.copy_into(incoming_writer);
future::select(a, b).await;
}
fn main() -> io::Result<()> {
task::block_on(async {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
let mut incoming = listener.incoming();
while let Some(incoming) = incoming.next().await {
let incoming = incoming?;
let outgoing = TcpStream::connect("127.0.0.1:3333").await?;
task::spawn(async {
handle(incoming, outgoing).await;
});
}
Ok(())
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.