Skip to content

Instantly share code, notes, and snippets.

@alichraghi
Last active November 20, 2022 17:44
Show Gist options
  • Save alichraghi/1707dc80a38d029d014780816c00ad13 to your computer and use it in GitHub Desktop.
Save alichraghi/1707dc80a38d029d014780816c00ad13 to your computer and use it in GitHub Desktop.
Simple Tokio Server
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0; 4096];
match socket.read(&mut buf).await {
// socket closed
Ok(_) => {
socket.write_all(b"HTTP/1.1 200 OK\r\n\r\n").await?;
}
Err(e) => {
println!("{}", e);
return;
}
};
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment