Crate asyncio

Source
Expand description

The asyncio is Asynchronous Input/Output library, that made based on boost::asio c++ library.

§Usage

This crate is on github and can be used by adding asyncio to the dependencies in your project’s Cargo.toml.

[dependencies]
rust_asio = "*"

And this in your crate root:

extern crate asyncio;

For example, TCP asynchronous connection code:

use asyncio::*;
use asyncio::ip::*;
use asyncio::socket_base::*;

use std::io;
use std::sync::{Arc, Mutex};

fn on_accept(sv: Arc<Mutex<TcpListener>>, res: io::Result<(TcpSocket, TcpEndpoint)>) {
  match res {
    Ok((soc, ep)) => { /* do something */ },
    Err(err) => panic!("{}", err),
  }
}

fn on_connect(cl: Arc<Mutex<TcpSocket>>, res: io::Result<()>) {
  match res {
    Ok(_) => { /* do something */ },
    Err(err) => panic!("{}", err),
  }
}

fn main() {
  let ctx = &IoContext::new().unwrap();

  let ep = TcpEndpoint::new(IpAddrV4::loopback(), 12345);
  let sv = TcpListener::new(ctx, ep.protocol()).unwrap();
  sv.set_option(ReuseAddr::new(true)).unwrap();
  sv.bind(&ep).unwrap();
  sv.listen().unwrap();
  let sv = Arc::new(Mutex::new(sv));
  sv.lock().unwrap().async_accept(wrap(on_accept, &sv));

  let cl = Arc::new(Mutex::new(TcpSocket::new(ctx, ep.protocol()).unwrap()));
  cl.lock().unwrap().async_connect(&ep, wrap(on_connect, &cl));

  ctx.run();
}

For example, TCP connection with coroutine code:

use asyncio::*;
use asyncio::ip::*;
use asyncio::socket_base::*;

fn main() {
  let ctx = &IoContext::new().unwrap();

  let ep = TcpEndpoint::new(IpAddrV4::loopback(), 12345);
  let mut sv = TcpListener::new(ctx, ep.protocol()).unwrap();
  sv.set_option(ReuseAddr::new(true)).unwrap();
  sv.bind(&ep).unwrap();
  sv.listen().unwrap();

  IoContext::spawn(ctx, move |co| {
    let (soc, ep) = sv.async_accept(co.wrap()).unwrap();
    /* do something */
  });

  IoContext::spawn(ctx, move |co| {
    let mut cl = TcpSocket::new(co.as_ctx(), ep.protocol()).unwrap();
    cl.async_connect(&ep, co.wrap()).unwrap();
    /* do something */
  });

  ctx.run();
}

Modules§

Structs§

Enums§

  • A list specifying POSIX categories of signal.

Traits§

Functions§

  • Provides a Arc handler to asynchronous operation.

Type Aliases§