Skip to content

Instantly share code, notes, and snippets.

@edsko
Created January 4, 2023 12:09
Show Gist options
  • Save edsko/f9372b1346ec31cffa459121266179a4 to your computer and use it in GitHub Desktop.
Save edsko/f9372b1346ec31cffa459121266179a4 to your computer and use it in GitHub Desktop.
use futures::StreamExt;
use quinn::{Connecting, Connection, Endpoint, ServerConfig};
use quinn_interop::{config, endpoint::stream::EndpointStream, insecure};
async fn server(config: ServerConfig) -> anyhow::Result<()> {
let endpoint = Endpoint::server(config, config::server_addr())?;
println!("Server setup");
// does not work
EndpointStream::new(&endpoint)
.for_each(handle_connection)
.await;
// works (accepts exactly one connection)
match endpoint.accept().await {
Some(connecting) => handle_connection(connecting).await,
None => (),
}
println!("Server terminating");
Ok(())
}
// This cannot return an error (because it's an argument to `for_each_concurrent`)
// TODO: We should handle errors a bit better though
async fn handle_connection(connecting: Connecting) {
println!("Connection established");
let connection: Connection = connecting.await.unwrap();
receive_bidirectional_stream(connection).await.unwrap()
}
async fn receive_bidirectional_stream(connection: Connection) -> anyhow::Result<()> {
while let Ok((mut send, recv)) = connection.accept_bi().await {
// Because it is a bidirectional stream, we can both send and receive.
println!("request: {:?}", recv.read_to_end(50).await?);
send.write_all(b"response").await?;
send.finish().await?;
}
Ok(())
}
#[tokio::main]
async fn main() {
let server_config = insecure::configure_server();
server(server_config).await.unwrap()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment