-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Examples: Improve Echo Example Consistency #7256
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
mod tcp { | ||
use bytes::Bytes; | ||
use futures::{future, Sink, SinkExt, Stream, StreamExt}; | ||
use std::{error::Error, io, net::SocketAddr}; | ||
use tokio::net::TcpStream; | ||
use tokio_util::codec::{BytesCodec, FramedRead, FramedWrite}; | ||
|
||
pub async fn connect( | ||
addr: &SocketAddr, | ||
mut stdin: impl Stream<Item = Result<Bytes, io::Error>> + Unpin, | ||
mut stdout: impl Sink<Bytes, Error = io::Error> + Unpin, | ||
) -> Result<(), Box<dyn Error>> { | ||
let mut stream = TcpStream::connect(addr).await?; | ||
let (r, w) = stream.split(); | ||
let mut sink = FramedWrite::new(w, BytesCodec::new()); | ||
// filter map Result<BytesMut, Error> stream into just a Bytes stream to match stdout Sink | ||
// on the event of an Error, log the error and end the stream | ||
let mut stream = FramedRead::new(r, BytesCodec::new()) | ||
.filter_map(|i| match i { | ||
//BytesMut into Bytes | ||
Ok(i) => future::ready(Some(i.freeze())), | ||
Err(e) => { | ||
println!("failed to read from socket; error={e}"); | ||
future::ready(None) | ||
} | ||
}) | ||
.map(Ok); | ||
|
||
match future::join(sink.send_all(&mut stdin), stdout.send_all(&mut stream)).await { | ||
(Err(e), _) | (_, Err(e)) => Err(e.into()), | ||
_ => Ok(()), | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Now that the code for TCP and UDP are moved to separate files, I think it makes sense to remove the mod tcp
and move the use
statements to the top of the file.
} | ||
} | ||
} | ||
|
||
mod udp { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same thing as connect-tcp.rs
here.
Motivation
This addresses the suggestion brought up in #7250.
Solution
This PR splits up
connect.rs
into two separate programs:connect-tcp.rs
andconnect-udp.rs
. This matches the echo examples which are split up by protocol already. This should improve readability and ease of understanding so end users only need to consider one protocol at a time.Additionally, documentation referencing these new example names has been updated appropriately. I tested these changes by running all examples that interact with these files and verifying that the behavior is the same as before.