Skip to content

Commit

Permalink
Merge pull request #67 from iamjpotts/20240319-improve-example
Browse files Browse the repository at this point in the history
Examples: Add additional logging of accepted connections
  • Loading branch information
softprops authored Mar 19, 2024
2 parents 70c0b8e + 0596ef9 commit 09f9806
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions examples/server.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use hyper::{service::service_fn, Response};
use hyper_util::rt::TokioIo;
use std::{error::Error, fs, path::Path};
use std::{error::Error, fs, io::ErrorKind, path::Path};
use tokio::net::UnixListener;

const PHRASE: &str = "It's a Unix system. I know this.";
const PHRASE: &str = "It's a Unix system. I know this.\n";

// Adapted from https://hyper.rs/guides/1/server/hello-world/
#[tokio::main]
Expand All @@ -16,16 +16,25 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {

let listener = UnixListener::bind(path)?;

println!("Listening for connections at {}.", path.display());

loop {
let (stream, _) = listener.accept().await?;
let io = TokioIo::new(stream);

println!("Accepting connection.");

tokio::task::spawn(async move {
let svc_fn = service_fn(|_req| async {
let body = PHRASE.to_string();
Ok::<_, hyper::Error>(Response::new(body))
});

// On linux, serve_connection will return right away with Result::Ok.
//
// On OSX, serve_connection will block until the client disconnects,
// and return Result::Err(hyper::Error) with a source (inner/cause)
// socket error indicating the client connection is no longer open.
match hyper::server::conn::http1::Builder::new()
.serve_connection(io, svc_fn)
.await
Expand All @@ -34,7 +43,17 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
println!("Accepted connection.");
}
Err(err) => {
eprintln!("Failed to accept connection: {err:?}");
let source: Option<&std::io::Error> =
err.source().and_then(|s| s.downcast_ref());

match source {
Some(io_err) if io_err.kind() == ErrorKind::NotConnected => {
println!("Client disconnected.");
}
_ => {
eprintln!("Failed to accept connection: {err:?}");
}
}
}
};
});
Expand Down

0 comments on commit 09f9806

Please sign in to comment.