Skip to content

Instantly share code, notes, and snippets.

@idontcalculate
Created September 3, 2024 17:02
Show Gist options
  • Save idontcalculate/54e04c5550940cf69adcc7dc53c11d22 to your computer and use it in GitHub Desktop.
Save idontcalculate/54e04c5550940cf69adcc7dc53c11d22 to your computer and use it in GitHub Desktop.
use io_uring::{IoUring, opcode, types::Fd};
use std::net::SocketAddr;
use std::os::fd::AsRawFd;
use tokio::net::{TcpListener, TcpStream};
use std::io::Result;
async fn handle_client(stream: TcpStream, ring: &mut IoUring) -> Result<()> {
let mut buf = [0; 1024];
// Prepare a read operation
let fd = Fd(stream.as_raw_fd());
let read_e = opcode::Recv::new(fd, buf.as_mut_ptr(), buf.len() as u32)
.build()
.user_data(0x42);
unsafe {
ring.submission()
.push(&read_e)
.expect("submission queue is full");
}
ring.submit_and_wait(1)?;
// Fetch the completion event
let cqe = ring.completion().next().expect("completion queue is empty");
if cqe.result() > 0 {
let response = b"HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nHello, world!";
// Prepare a write operation
let write_e = opcode::Send::new(fd, response.as_ptr(), response.len() as u32)
.build()
.user_data(0x43);
unsafe {
ring.submission()
.push(&write_e)
.expect("submission queue is full");
}
ring.submit_and_wait(1)?;
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
let addr = "127.0.0.1:8080".parse::<SocketAddr>().unwrap();
let listener = TcpListener::bind(addr).await.unwrap();
let mut ring = IoUring::new(256)?;
loop {
let (stream, _) = listener.accept().await?;
handle_client(stream, &mut ring).await?;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment