-
Notifications
You must be signed in to change notification settings - Fork 743
Description
I just spent about an hour trying to understand the simpleserver example to make a simple TLS stream over TCP:
rustls/examples/src/bin/simpleserver.rs
Lines 41 to 49 in 6cc7a45
let mut conn = rustls::ServerConnection::new(Arc::new(config))?; | |
conn.complete_io(&mut stream)?; | |
conn.writer() | |
.write_all(b"Hello from the server")?; | |
conn.complete_io(&mut stream)?; | |
let mut buf = [0; 64]; | |
let len = conn.reader().read(&mut buf)?; | |
println!("Received message from client: {:?}", &buf[..len]); |
because I was thrown off by the fact that we don't pass the
TcpStream
when creating the ServerConnection
, and that seemed to imply that this example (using conn.reader()
as my final reader) would not work if the message was too large, because it was unclear to me how it would be able to still refer to the TcpStream
when doing many calls to read
on that...
Only to finally figure out that one can actually use rustls::Stream
, like on the client side, to get a working stream with none of the crazy read_tls()
/write_tls()
/complete_io()
concerns.
My question is, why is that example not using that already?
The current writing seems error-prone: people might not immediately notice that they need to interlace calls to read
on the connection.reader()
and calls to complete_io
, or actually just use Stream
instead.
I could just as well have not noticed that we don't pass the TcpStream
when creating the ServerConnection
...
New proposed writing:
let listener = TcpListener::bind(format!("[::]:{}", 4443)).unwrap();
let (mut tcp_stream, _) = listener.accept()?;
let mut conn = rustls::ServerConnection::new(Arc::new(config))?;
let mut tls_stream = rustls::Stream::new(&mut conn, &mut tcp_stream);
tls_stream.write_all(b"Hello from the server")?;
let mut buf = [0; 64];
let len = tls_stream.read(&mut buf)?;
println!("Received message from client: {:?}", &buf[..len]);
@cpu since you authored the relevant file
(I can open a PR if you like)