Non-blocking networking sockets

While the simple HTTP connections from the previous chapter are easy to implement, they are not ready for production use. If the program can only have one connection open at a time (e.g., blocking), the fast CPU would be waiting for the slow network. Non-blocking I/O means that the application program can keep multiple connections open at the same time, and process data in and out of those connections as they come in. The program can either alternatingly poll those open connections or wait for incoming data to trigger async functions. That allows I/O intensive programs to run much faster even in a single-threaded environment. In this chapter, we will cover both polling and async programming models.

A non-blocking HTTP client example

The source code for a non-blocking HTTP client application is available. The following main() function starts two HTTP connections. The program keeps both connections open, and alternatingly checks for incoming data from them. In another word, the two connections are not blocking each other. Their data are handled concurrently (or alternatingly) as the data comes in.

  1. use httparse::{Response, EMPTY_HEADER};
  2. use std::io::{self, Read, Write};
  3. use std::str::from_utf8;
  4. use wasmedge_wasi_socket::TcpStream;
  5. fn main() {
  6. let req = "GET / HTTP/1.0\n\n";
  7. let mut first_connection = TcpStream::connect("127.0.0.1:80").unwrap();
  8. first_connection.set_nonblocking(true).unwrap();
  9. first_connection.write_all(req.as_bytes()).unwrap();
  10. let mut second_connection = TcpStream::connect("127.0.0.1:80").unwrap();
  11. second_connection.set_nonblocking(true).unwrap();
  12. second_connection.write_all(req.as_bytes()).unwrap();
  13. let mut first_buf = vec![0; 4096];
  14. let mut first_bytes_read = 0;
  15. let mut second_buf = vec![0; 4096];
  16. let mut second_bytes_read = 0;
  17. loop {
  18. let mut first_complete = false;
  19. let mut second_complete = false;
  20. if !first_complete {
  21. match read_data(&mut first_connection, &mut first_buf, first_bytes_read) {
  22. Ok((bytes_read, false)) => {
  23. first_bytes_read = bytes_read;
  24. }
  25. Ok((bytes_read, true)) => {
  26. println!("First connection completed");
  27. if bytes_read != 0 {
  28. parse_data(&first_buf, bytes_read);
  29. }
  30. first_complete = true;
  31. }
  32. Err(e) => {
  33. println!("First connection error: {}", e);
  34. first_complete = true;
  35. }
  36. }
  37. }
  38. if !second_complete {
  39. match read_data(&mut second_connection, &mut second_buf, second_bytes_read) {
  40. Ok((bytes_read, false)) => {
  41. second_bytes_read = bytes_read;
  42. }
  43. Ok((bytes_read, true)) => {
  44. println!("Second connection completed");
  45. if bytes_read != 0 {
  46. parse_data(&second_buf, bytes_read);
  47. }
  48. second_complete = true;
  49. }
  50. Err(e) => {
  51. println!("Second connection error: {}", e);
  52. second_complete = true;
  53. }
  54. }
  55. }
  56. if first_complete && second_complete {
  57. break;
  58. }
  59. }
  60. }

The following command compiles the Rust program.

cargo build --target wasm32-wasi --release

The following command runs the application in WasmEdge.

  1. #![allow(unused)]
  2. fn main() {
  3. wasmedge target/wasm32-wasi/release/nonblock_http_client.wasm
  4. }

A non-blocking HTTP server example

The source code for a non-blocking HTTP server application is available. The following main() function starts an HTTP server. It receives events from multiple open connections, and processes those events as they are received by calling the async handler functions registered to each connection. This server can process events from multiple open connections concurrently.

  1. fn main() -> std::io::Result<()> {
  2. let mut poll = Poll::new();
  3. let server = TcpListener::bind("127.0.0.1:1234", true)?;
  4. println!("Listening on 127.0.0.1:1234");
  5. let mut connections = HashMap::new();
  6. let mut handlers = HashMap::new();
  7. const SERVER: Token = Token(0);
  8. let mut unique_token = Token(SERVER.0 + 1);
  9. poll.register(&server, SERVER, Interest::Read);
  10. loop {
  11. let events = poll.poll().unwrap();
  12. for event in events {
  13. match event.token {
  14. SERVER => loop {
  15. let (connection, address) = match server.accept(FDFLAGS_NONBLOCK) {
  16. Ok((connection, address)) => (connection, address),
  17. Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
  18. Err(e) => panic!("accept error: {}", e),
  19. };
  20. println!("Accepted connection from: {}", address);
  21. let token = unique_token.add();
  22. poll.register(&connection, token, Interest::Read);
  23. connections.insert(token, connection);
  24. },
  25. token => {
  26. let done = if let Some(connection) = connections.get_mut(&token) {
  27. let handler = match handlers.get_mut(&token) {
  28. Some(handler) => handler,
  29. None => {
  30. let handler = Handler::new();
  31. handlers.insert(token, handler);
  32. handlers.get_mut(&token).unwrap()
  33. }
  34. };
  35. handle_connection(&mut poll, connection, handler, &event)?
  36. } else {
  37. false
  38. };
  39. if done {
  40. if let Some(connection) = connections.remove(&token) {
  41. connection.shutdown(Shutdown::Both)?;
  42. poll.unregister(&connection);
  43. handlers.remove(&token);
  44. }
  45. }
  46. }
  47. }
  48. }
  49. }
  50. }

The handle_connection() function processes the data from those open connections. In this case, it just writes the request body into the response. It is also done asynchronously — meaning that the handle_connection() function creates an event for the response, and puts it in the queue. The main application loop processes the event and sends the response when it is waiting for data from other connections.

  1. #![allow(unused)]
  2. fn main() {
  3. fn handle_connection(
  4. poll: &mut Poll,
  5. connection: &mut TcpStream,
  6. handler: &mut Handler,
  7. event: &Event,
  8. ) -> io::Result<bool> {
  9. if event.is_readable() {
  10. let mut connection_closed = false;
  11. let mut received_data = vec![0; 4096];
  12. let mut bytes_read = 0;
  13. loop {
  14. match connection.read(&mut received_data[bytes_read..]) {
  15. Ok(0) => {
  16. connection_closed = true;
  17. break;
  18. }
  19. Ok(n) => {
  20. bytes_read += n;
  21. if bytes_read == received_data.len() {
  22. received_data.resize(received_data.len() + 1024, 0);
  23. }
  24. }
  25. Err(ref err) if would_block(err) => {
  26. if bytes_read != 0 {
  27. let received_data = &received_data[..bytes_read];
  28. let mut bs: parsed::stream::ByteStream =
  29. match String::from_utf8(received_data.to_vec()) {
  30. Ok(s) => s,
  31. Err(_) => {
  32. continue;
  33. }
  34. }
  35. .into();
  36. let req = match parsed::http::parse_http_request(&mut bs) {
  37. Some(req) => req,
  38. None => {
  39. break;
  40. }
  41. };
  42. for header in req.headers.iter() {
  43. if header.name.eq("Conntent-Length") {
  44. let content_length = header.value.parse::<usize>().unwrap();
  45. if content_length > received_data.len() {
  46. return Ok(true);
  47. }
  48. }
  49. }
  50. println!(
  51. "{:?} request: {:?} {:?}",
  52. connection.peer_addr().unwrap(),
  53. req.method,
  54. req.path
  55. );
  56. let res = Response {
  57. protocol: "HTTP/1.1".to_string(),
  58. code: 200,
  59. message: "OK".to_string(),
  60. headers: vec![
  61. Header {
  62. name: "Content-Length".to_string(),
  63. value: req.content.len().to_string(),
  64. },
  65. Header {
  66. name: "Connection".to_string(),
  67. value: "close".to_string(),
  68. },
  69. ],
  70. content: req.content,
  71. };
  72. handler.response = Some(res.into());
  73. poll.reregister(connection, event.token, Interest::Write);
  74. break;
  75. } else {
  76. println!("Empty request");
  77. return Ok(true);
  78. }
  79. }
  80. Err(ref err) if interrupted(err) => continue,
  81. Err(err) => return Err(err),
  82. }
  83. }
  84. if connection_closed {
  85. println!("Connection closed");
  86. return Ok(true);
  87. }
  88. }
  89. if event.is_writable() && handler.response.is_some() {
  90. let resp = handler.response.clone().unwrap();
  91. match connection.write(resp.as_bytes()) {
  92. Ok(n) if n < resp.len() => return Err(io::ErrorKind::WriteZero.into()),
  93. Ok(_) => {
  94. return Ok(true);
  95. }
  96. Err(ref err) if would_block(err) => {}
  97. Err(ref err) if interrupted(err) => {
  98. return handle_connection(poll, connection, handler, event)
  99. }
  100. Err(err) => return Err(err),
  101. }
  102. }
  103. Ok(false)
  104. }
  105. }

The following command compiles the Rust program.

cargo build --target wasm32-wasi --release

The following command runs the application in WasmEdge.

$ wasmedge target/wasm32-wasi/release/poll_http_server.wasm new connection at 1234

To test the HTTP server, you can submit a HTTP request to it via curl.

$ curl -d "name=WasmEdge" -X POST http://127.0.0.1:1234 echo: name=WasmEdge