pub struct Async<T> { /* private fields */ }
Expand description
Async adapter for I/O types.
This type puts an I/O handle into non-blocking mode, registers it in epoll/kqueue/event ports/wepoll, and then provides an async interface for it.
Caveats
Async
is a low-level primitive, and as such it comes with some caveats.
For higher-level primitives built on top of Async
, look into async-net
or
async-process
(on Unix).
Supported types
Async
supports all networking types, as well as some OS-specific file descriptors like
timerfd and inotify.
However, do not use Async
with types like File
,
Stdin
, Stdout
, or Stderr
because all operating systems have issues with them when put in non-blocking mode.
Concurrent I/O
Note that &Async<T>
implements AsyncRead
and AsyncWrite
if &T
implements those traits, which means tasks can concurrently read and write using shared
references.
But there is a catch: only one task can read a time, and only one task can write at a time. It is okay to have two tasks where one is reading and the other is writing at the same time, but it is not okay to have two tasks reading at the same time or writing at the same time. If you try to do that, conflicting tasks will just keep waking each other in turn, thus wasting CPU time.
Besides AsyncRead
and AsyncWrite
, this caveat also applies to
poll_readable()
and
poll_writable()
.
However, any number of tasks can be concurrently calling other methods like
readable()
or read_with()
.
Closing
Closing the write side of Async
with close()
simply flushes. If you want to shutdown a TCP or Unix socket, use
Shutdown
.
Examples
Connect to a server and echo incoming messages back to the server:
use async_io::Async;
use futures_lite::io;
use std::net::TcpStream;
// Connect to a local server.
let stream = Async::<TcpStream>::connect(([127, 0, 0, 1], 8000)).await?;
// Echo all messages from the read side of the stream into the write side.
io::copy(&stream, &stream).await?;
You can use either predefined async methods or wrap blocking I/O operations in
Async::read_with()
, Async::read_with_mut()
, Async::write_with()
, and
Async::write_with_mut()
:
use async_io::Async;
use std::net::TcpListener;
let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
// These two lines are equivalent:
let (stream, addr) = listener.accept().await?;
let (stream, addr) = listener.read_with(|inner| inner.accept()).await?;
Implementations
sourceimpl<T> Async<T> where
T: AsRawFd,
impl<T> Async<T> where
T: AsRawFd,
sourcepub fn new(io: T) -> Result<Async<T>, Error>
pub fn new(io: T) -> Result<Async<T>, Error>
Creates an async I/O handle.
This method will put the handle in non-blocking mode and register it in epoll/kqueue/event ports/wepoll.
On Unix systems, the handle must implement AsRawFd
, while on Windows it must implement
AsRawSocket
.
Examples
use async_io::Async;
use std::net::{SocketAddr, TcpListener};
let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))?;
let listener = Async::new(listener)?;
sourceimpl<T> Async<T>
impl<T> Async<T>
sourcepub fn get_ref(&self) -> &T
pub fn get_ref(&self) -> &T
Gets a reference to the inner I/O handle.
Examples
use async_io::Async;
use std::net::TcpListener;
let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
let inner = listener.get_ref();
sourcepub fn get_mut(&mut self) -> &mut T
pub fn get_mut(&mut self) -> &mut T
Gets a mutable reference to the inner I/O handle.
Examples
use async_io::Async;
use std::net::TcpListener;
let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
let inner = listener.get_mut();
sourcepub fn into_inner(self) -> Result<T, Error>
pub fn into_inner(self) -> Result<T, Error>
Unwraps the inner I/O handle.
This method will not put the I/O handle back into blocking mode.
Examples
use async_io::Async;
use std::net::TcpListener;
let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
let inner = listener.into_inner()?;
// Put the listener back into blocking mode.
inner.set_nonblocking(false)?;
sourcepub fn readable(&self) -> Readable<'_, T>ⓘNotable traits for Readable<'_, T>impl<'_, T> Future for Readable<'_, T> type Output = Result<(), Error>;
pub fn readable(&self) -> Readable<'_, T>ⓘNotable traits for Readable<'_, T>impl<'_, T> Future for Readable<'_, T> type Output = Result<(), Error>;
Waits until the I/O handle is readable.
This method completes when a read operation on this I/O handle wouldn’t block.
Examples
use async_io::Async;
use std::net::TcpListener;
let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
// Wait until a client can be accepted.
listener.readable().await?;
sourcepub fn readable_owned(self: Arc<Async<T>>) -> ReadableOwned<T>ⓘNotable traits for ReadableOwned<T>impl<T> Future for ReadableOwned<T> type Output = Result<(), Error>;
pub fn readable_owned(self: Arc<Async<T>>) -> ReadableOwned<T>ⓘNotable traits for ReadableOwned<T>impl<T> Future for ReadableOwned<T> type Output = Result<(), Error>;
Waits until the I/O handle is readable.
This method completes when a read operation on this I/O handle wouldn’t block.
sourcepub fn writable(&self) -> Writable<'_, T>ⓘNotable traits for Writable<'_, T>impl<'_, T> Future for Writable<'_, T> type Output = Result<(), Error>;
pub fn writable(&self) -> Writable<'_, T>ⓘNotable traits for Writable<'_, T>impl<'_, T> Future for Writable<'_, T> type Output = Result<(), Error>;
Waits until the I/O handle is writable.
This method completes when a write operation on this I/O handle wouldn’t block.
Examples
use async_io::Async;
use std::net::{TcpStream, ToSocketAddrs};
let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
let stream = Async::<TcpStream>::connect(addr).await?;
// Wait until the stream is writable.
stream.writable().await?;
sourcepub fn writable_owned(self: Arc<Async<T>>) -> WritableOwned<T>ⓘNotable traits for WritableOwned<T>impl<T> Future for WritableOwned<T> type Output = Result<(), Error>;
pub fn writable_owned(self: Arc<Async<T>>) -> WritableOwned<T>ⓘNotable traits for WritableOwned<T>impl<T> Future for WritableOwned<T> type Output = Result<(), Error>;
Waits until the I/O handle is writable.
This method completes when a write operation on this I/O handle wouldn’t block.
sourcepub fn poll_readable(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>
pub fn poll_readable(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>
Polls the I/O handle for readability.
When this method returns Poll::Ready
, that means the OS has delivered an event
indicating readability since the last time this task has called the method and received
Poll::Pending
.
Caveats
Two different tasks should not call this method concurrently. Otherwise, conflicting tasks will just keep waking each other in turn, thus wasting CPU time.
Note that the AsyncRead
implementation for Async
also uses this method.
Examples
use async_io::Async;
use futures_lite::future;
use std::net::TcpListener;
let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
// Wait until a client can be accepted.
future::poll_fn(|cx| listener.poll_readable(cx)).await?;
sourcepub fn poll_writable(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>
pub fn poll_writable(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>
Polls the I/O handle for writability.
When this method returns Poll::Ready
, that means the OS has delivered an event
indicating writability since the last time this task has called the method and received
Poll::Pending
.
Caveats
Two different tasks should not call this method concurrently. Otherwise, conflicting tasks will just keep waking each other in turn, thus wasting CPU time.
Note that the AsyncWrite
implementation for Async
also uses this method.
Examples
use async_io::Async;
use futures_lite::future;
use std::net::{TcpStream, ToSocketAddrs};
let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
let stream = Async::<TcpStream>::connect(addr).await?;
// Wait until the stream is writable.
future::poll_fn(|cx| stream.poll_writable(cx)).await?;
sourcepub async fn read_with<R>(
&'_ self,
op: impl FnMut(&T) -> Result<R, Error>
) -> Result<R, Error>
pub async fn read_with<R>(
&'_ self,
op: impl FnMut(&T) -> Result<R, Error>
) -> Result<R, Error>
Performs a read operation asynchronously.
The I/O handle is registered in the reactor and put in non-blocking mode. This method
invokes the op
closure in a loop until it succeeds or returns an error other than
io::ErrorKind::WouldBlock
. In between iterations of the loop, it waits until the OS
sends a notification that the I/O handle is readable.
The closure receives a shared reference to the I/O handle.
Examples
use async_io::Async;
use std::net::TcpListener;
let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
// Accept a new client asynchronously.
let (stream, addr) = listener.read_with(|l| l.accept()).await?;
sourcepub async fn read_with_mut<R>(
&'_ mut self,
op: impl FnMut(&mut T) -> Result<R, Error>
) -> Result<R, Error>
pub async fn read_with_mut<R>(
&'_ mut self,
op: impl FnMut(&mut T) -> Result<R, Error>
) -> Result<R, Error>
Performs a read operation asynchronously.
The I/O handle is registered in the reactor and put in non-blocking mode. This method
invokes the op
closure in a loop until it succeeds or returns an error other than
io::ErrorKind::WouldBlock
. In between iterations of the loop, it waits until the OS
sends a notification that the I/O handle is readable.
The closure receives a mutable reference to the I/O handle.
Examples
use async_io::Async;
use std::net::TcpListener;
let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
// Accept a new client asynchronously.
let (stream, addr) = listener.read_with_mut(|l| l.accept()).await?;
sourcepub async fn write_with<R>(
&'_ self,
op: impl FnMut(&T) -> Result<R, Error>
) -> Result<R, Error>
pub async fn write_with<R>(
&'_ self,
op: impl FnMut(&T) -> Result<R, Error>
) -> Result<R, Error>
Performs a write operation asynchronously.
The I/O handle is registered in the reactor and put in non-blocking mode. This method
invokes the op
closure in a loop until it succeeds or returns an error other than
io::ErrorKind::WouldBlock
. In between iterations of the loop, it waits until the OS
sends a notification that the I/O handle is writable.
The closure receives a shared reference to the I/O handle.
Examples
use async_io::Async;
use std::net::UdpSocket;
let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;
let msg = b"hello";
let len = socket.write_with(|s| s.send(msg)).await?;
sourcepub async fn write_with_mut<R>(
&'_ mut self,
op: impl FnMut(&mut T) -> Result<R, Error>
) -> Result<R, Error>
pub async fn write_with_mut<R>(
&'_ mut self,
op: impl FnMut(&mut T) -> Result<R, Error>
) -> Result<R, Error>
Performs a write operation asynchronously.
The I/O handle is registered in the reactor and put in non-blocking mode. This method
invokes the op
closure in a loop until it succeeds or returns an error other than
io::ErrorKind::WouldBlock
. In between iterations of the loop, it waits until the OS
sends a notification that the I/O handle is writable.
The closure receives a mutable reference to the I/O handle.
Examples
use async_io::Async;
use std::net::UdpSocket;
let mut socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;
let msg = b"hello";
let len = socket.write_with_mut(|s| s.send(msg)).await?;
sourceimpl Async<TcpListener>
impl Async<TcpListener>
sourcepub fn bind<A>(addr: A) -> Result<Async<TcpListener>, Error> where
A: Into<SocketAddr>,
pub fn bind<A>(addr: A) -> Result<Async<TcpListener>, Error> where
A: Into<SocketAddr>,
Creates a TCP listener bound to the specified address.
Binding with port number 0 will request an available port from the OS.
Examples
use async_io::Async;
use std::net::TcpListener;
let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
println!("Listening on {}", listener.get_ref().local_addr()?);
sourcepub async fn accept(&'_ self) -> Result<(Async<TcpStream>, SocketAddr), Error>
pub async fn accept(&'_ self) -> Result<(Async<TcpStream>, SocketAddr), Error>
Accepts a new incoming TCP connection.
When a connection is established, it will be returned as a TCP stream together with its remote address.
Examples
use async_io::Async;
use std::net::TcpListener;
let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?;
let (stream, addr) = listener.accept().await?;
println!("Accepted client: {}", addr);
sourcepub fn incoming(
&self
) -> impl Stream<Item = Result<Async<TcpStream>, Error>> + Send
pub fn incoming(
&self
) -> impl Stream<Item = Result<Async<TcpStream>, Error>> + Send
Returns a stream of incoming TCP connections.
The stream is infinite, i.e. it never stops with a None
.
Examples
use async_io::Async;
use futures_lite::{pin, stream::StreamExt};
use std::net::TcpListener;
let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?;
let incoming = listener.incoming();
pin!(incoming);
while let Some(stream) = incoming.next().await {
let stream = stream?;
println!("Accepted client: {}", stream.get_ref().peer_addr()?);
}
sourceimpl Async<TcpStream>
impl Async<TcpStream>
sourcepub async fn connect<A>(addr: A) -> Result<Async<TcpStream>, Error> where
A: Into<SocketAddr>,
pub async fn connect<A>(addr: A) -> Result<Async<TcpStream>, Error> where
A: Into<SocketAddr>,
Creates a TCP connection to the specified address.
Examples
use async_io::Async;
use std::net::{TcpStream, ToSocketAddrs};
let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
let stream = Async::<TcpStream>::connect(addr).await?;
sourcepub async fn peek(&'_ self, buf: &'_ mut [u8]) -> Result<usize, Error>
pub async fn peek(&'_ self, buf: &'_ mut [u8]) -> Result<usize, Error>
Reads data from the stream without removing it from the buffer.
Returns the number of bytes read. Successive calls of this method read the same data.
Examples
use async_io::Async;
use futures_lite::{io::AsyncWriteExt, stream::StreamExt};
use std::net::{TcpStream, ToSocketAddrs};
let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
let mut stream = Async::<TcpStream>::connect(addr).await?;
stream
.write_all(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
.await?;
let mut buf = [0u8; 1024];
let len = stream.peek(&mut buf).await?;
sourceimpl Async<UdpSocket>
impl Async<UdpSocket>
sourcepub fn bind<A>(addr: A) -> Result<Async<UdpSocket>, Error> where
A: Into<SocketAddr>,
pub fn bind<A>(addr: A) -> Result<Async<UdpSocket>, Error> where
A: Into<SocketAddr>,
Creates a UDP socket bound to the specified address.
Binding with port number 0 will request an available port from the OS.
Examples
use async_io::Async;
use std::net::UdpSocket;
let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 0))?;
println!("Bound to {}", socket.get_ref().local_addr()?);
sourcepub async fn recv_from(
&'_ self,
buf: &'_ mut [u8]
) -> Result<(usize, SocketAddr), Error>
pub async fn recv_from(
&'_ self,
buf: &'_ mut [u8]
) -> Result<(usize, SocketAddr), Error>
Receives a single datagram message.
Returns the number of bytes read and the address the message came from.
This method must be called with a valid byte slice of sufficient size to hold the message. If the message is too long to fit, excess bytes may get discarded.
Examples
use async_io::Async;
use std::net::UdpSocket;
let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
let mut buf = [0u8; 1024];
let (len, addr) = socket.recv_from(&mut buf).await?;
sourcepub async fn peek_from(
&'_ self,
buf: &'_ mut [u8]
) -> Result<(usize, SocketAddr), Error>
pub async fn peek_from(
&'_ self,
buf: &'_ mut [u8]
) -> Result<(usize, SocketAddr), Error>
Receives a single datagram message without removing it from the queue.
Returns the number of bytes read and the address the message came from.
This method must be called with a valid byte slice of sufficient size to hold the message. If the message is too long to fit, excess bytes may get discarded.
Examples
use async_io::Async;
use std::net::UdpSocket;
let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
let mut buf = [0u8; 1024];
let (len, addr) = socket.peek_from(&mut buf).await?;
sourcepub async fn send_to<A>(
&'_ self,
buf: &'_ [u8],
addr: A
) -> Result<usize, Error> where
A: Into<SocketAddr>,
pub async fn send_to<A>(
&'_ self,
buf: &'_ [u8],
addr: A
) -> Result<usize, Error> where
A: Into<SocketAddr>,
Sends data to the specified address.
Returns the number of bytes writen.
Examples
use async_io::Async;
use std::net::UdpSocket;
let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 0))?;
let addr = socket.get_ref().local_addr()?;
let msg = b"hello";
let len = socket.send_to(msg, addr).await?;
sourcepub async fn recv(&'_ self, buf: &'_ mut [u8]) -> Result<usize, Error>
pub async fn recv(&'_ self, buf: &'_ mut [u8]) -> Result<usize, Error>
Receives a single datagram message from the connected peer.
Returns the number of bytes read.
This method must be called with a valid byte slice of sufficient size to hold the message. If the message is too long to fit, excess bytes may get discarded.
The connect
method connects this socket to a remote address.
This method will fail if the socket is not connected.
Examples
use async_io::Async;
use std::net::UdpSocket;
let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;
let mut buf = [0u8; 1024];
let len = socket.recv(&mut buf).await?;
sourcepub async fn peek(&'_ self, buf: &'_ mut [u8]) -> Result<usize, Error>
pub async fn peek(&'_ self, buf: &'_ mut [u8]) -> Result<usize, Error>
Receives a single datagram message from the connected peer without removing it from the queue.
Returns the number of bytes read and the address the message came from.
This method must be called with a valid byte slice of sufficient size to hold the message. If the message is too long to fit, excess bytes may get discarded.
The connect
method connects this socket to a remote address.
This method will fail if the socket is not connected.
Examples
use async_io::Async;
use std::net::UdpSocket;
let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;
let mut buf = [0u8; 1024];
let len = socket.peek(&mut buf).await?;
sourcepub async fn send(&'_ self, buf: &'_ [u8]) -> Result<usize, Error>
pub async fn send(&'_ self, buf: &'_ [u8]) -> Result<usize, Error>
Sends data to the connected peer.
Returns the number of bytes written.
The connect
method connects this socket to a remote address.
This method will fail if the socket is not connected.
Examples
use async_io::Async;
use std::net::UdpSocket;
let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;
let msg = b"hello";
let len = socket.send(msg).await?;
sourceimpl Async<UnixListener>
impl Async<UnixListener>
sourcepub fn bind<P>(path: P) -> Result<Async<UnixListener>, Error> where
P: AsRef<Path>,
pub fn bind<P>(path: P) -> Result<Async<UnixListener>, Error> where
P: AsRef<Path>,
Creates a UDS listener bound to the specified path.
Examples
use async_io::Async;
use std::os::unix::net::UnixListener;
let listener = Async::<UnixListener>::bind("/tmp/socket")?;
println!("Listening on {:?}", listener.get_ref().local_addr()?);
sourcepub async fn accept(&'_ self) -> Result<(Async<UnixStream>, SocketAddr), Error>
pub async fn accept(&'_ self) -> Result<(Async<UnixStream>, SocketAddr), Error>
Accepts a new incoming UDS stream connection.
When a connection is established, it will be returned as a stream together with its remote address.
Examples
use async_io::Async;
use std::os::unix::net::UnixListener;
let listener = Async::<UnixListener>::bind("/tmp/socket")?;
let (stream, addr) = listener.accept().await?;
println!("Accepted client: {:?}", addr);
sourcepub fn incoming(
&self
) -> impl Stream<Item = Result<Async<UnixStream>, Error>> + Send
pub fn incoming(
&self
) -> impl Stream<Item = Result<Async<UnixStream>, Error>> + Send
Returns a stream of incoming UDS connections.
The stream is infinite, i.e. it never stops with a None
item.
Examples
use async_io::Async;
use futures_lite::{pin, stream::StreamExt};
use std::os::unix::net::UnixListener;
let listener = Async::<UnixListener>::bind("/tmp/socket")?;
let incoming = listener.incoming();
pin!(incoming);
while let Some(stream) = incoming.next().await {
let stream = stream?;
println!("Accepted client: {:?}", stream.get_ref().peer_addr()?);
}
sourceimpl Async<UnixStream>
impl Async<UnixStream>
sourceimpl Async<UnixDatagram>
impl Async<UnixDatagram>
sourcepub fn bind<P>(path: P) -> Result<Async<UnixDatagram>, Error> where
P: AsRef<Path>,
pub fn bind<P>(path: P) -> Result<Async<UnixDatagram>, Error> where
P: AsRef<Path>,
Creates a UDS datagram socket bound to the specified path.
Examples
use async_io::Async;
use std::os::unix::net::UnixDatagram;
let socket = Async::<UnixDatagram>::bind("/tmp/socket")?;
sourcepub fn unbound() -> Result<Async<UnixDatagram>, Error>
pub fn unbound() -> Result<Async<UnixDatagram>, Error>
Creates a UDS datagram socket not bound to any address.
Examples
use async_io::Async;
use std::os::unix::net::UnixDatagram;
let socket = Async::<UnixDatagram>::unbound()?;
sourcepub fn pair() -> Result<(Async<UnixDatagram>, Async<UnixDatagram>), Error>
pub fn pair() -> Result<(Async<UnixDatagram>, Async<UnixDatagram>), Error>
Creates an unnamed pair of connected Unix datagram sockets.
Examples
use async_io::Async;
use std::os::unix::net::UnixDatagram;
let (socket1, socket2) = Async::<UnixDatagram>::pair()?;
sourcepub async fn recv_from(
&'_ self,
buf: &'_ mut [u8]
) -> Result<(usize, SocketAddr), Error>
pub async fn recv_from(
&'_ self,
buf: &'_ mut [u8]
) -> Result<(usize, SocketAddr), Error>
Receives data from the socket.
Returns the number of bytes read and the address the message came from.
Examples
use async_io::Async;
use std::os::unix::net::UnixDatagram;
let socket = Async::<UnixDatagram>::bind("/tmp/socket")?;
let mut buf = [0u8; 1024];
let (len, addr) = socket.recv_from(&mut buf).await?;
sourcepub async fn send_to<P>(
&'_ self,
buf: &'_ [u8],
path: P
) -> Result<usize, Error> where
P: AsRef<Path>,
pub async fn send_to<P>(
&'_ self,
buf: &'_ [u8],
path: P
) -> Result<usize, Error> where
P: AsRef<Path>,
Sends data to the specified address.
Returns the number of bytes written.
Examples
use async_io::Async;
use std::os::unix::net::UnixDatagram;
let socket = Async::<UnixDatagram>::unbound()?;
let msg = b"hello";
let addr = "/tmp/socket";
let len = socket.send_to(msg, addr).await?;
sourcepub async fn recv(&'_ self, buf: &'_ mut [u8]) -> Result<usize, Error>
pub async fn recv(&'_ self, buf: &'_ mut [u8]) -> Result<usize, Error>
Receives data from the connected peer.
Returns the number of bytes read and the address the message came from.
The connect
method connects this socket to a remote address.
This method will fail if the socket is not connected.
Examples
use async_io::Async;
use std::os::unix::net::UnixDatagram;
let socket = Async::<UnixDatagram>::bind("/tmp/socket1")?;
socket.get_ref().connect("/tmp/socket2")?;
let mut buf = [0u8; 1024];
let len = socket.recv(&mut buf).await?;
sourcepub async fn send(&'_ self, buf: &'_ [u8]) -> Result<usize, Error>
pub async fn send(&'_ self, buf: &'_ [u8]) -> Result<usize, Error>
Sends data to the connected peer.
Returns the number of bytes written.
The connect
method connects this socket to a remote address.
This method will fail if the socket is not connected.
Examples
use async_io::Async;
use std::os::unix::net::UnixDatagram;
let socket = Async::<UnixDatagram>::bind("/tmp/socket1")?;
socket.get_ref().connect("/tmp/socket2")?;
let msg = b"hello";
let len = socket.send(msg).await?;
Trait Implementations
sourceimpl<T> AsyncRead for Async<T> where
T: Read,
impl<T> AsyncRead for Async<T> where
T: Read,
sourceimpl<'_, T> AsyncRead for &'_ Async<T> where
&'a T: for<'a> Read,
impl<'_, T> AsyncRead for &'_ Async<T> where
&'a T: for<'a> Read,
sourceimpl<'_, T> AsyncWrite for &'_ Async<T> where
&'a T: for<'a> Write,
impl<'_, T> AsyncWrite for &'_ Async<T> where
&'a T: for<'a> Write,
sourcefn poll_write(
self: Pin<&mut &'_ Async<T>>,
cx: &mut Context<'_>,
buf: &[u8]
) -> Poll<Result<usize, Error>>
fn poll_write(
self: Pin<&mut &'_ Async<T>>,
cx: &mut Context<'_>,
buf: &[u8]
) -> Poll<Result<usize, Error>>
Attempt to write bytes from buf
into the object. Read more
sourcefn poll_write_vectored(
self: Pin<&mut &'_ Async<T>>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>]
) -> Poll<Result<usize, Error>>
fn poll_write_vectored(
self: Pin<&mut &'_ Async<T>>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>]
) -> Poll<Result<usize, Error>>
Attempt to write bytes from bufs
into the object using vectored
IO operations. Read more
sourceimpl<T> AsyncWrite for Async<T> where
T: Write,
impl<T> AsyncWrite for Async<T> where
T: Write,
sourcefn poll_write(
self: Pin<&mut Async<T>>,
cx: &mut Context<'_>,
buf: &[u8]
) -> Poll<Result<usize, Error>>
fn poll_write(
self: Pin<&mut Async<T>>,
cx: &mut Context<'_>,
buf: &[u8]
) -> Poll<Result<usize, Error>>
Attempt to write bytes from buf
into the object. Read more
sourcefn poll_write_vectored(
self: Pin<&mut Async<T>>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>]
) -> Poll<Result<usize, Error>>
fn poll_write_vectored(
self: Pin<&mut Async<T>>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>]
) -> Poll<Result<usize, Error>>
Attempt to write bytes from bufs
into the object using vectored
IO operations. Read more
sourceimpl From<Async<TcpListener>> for TcpListener
impl From<Async<TcpListener>> for TcpListener
sourcefn from(listener: Async<TcpListener>) -> TcpListener
fn from(listener: Async<TcpListener>) -> TcpListener
Performs the conversion.
sourceimpl From<Async<UnixDatagram>> for UnixDatagram
impl From<Async<UnixDatagram>> for UnixDatagram
sourcefn from(socket: Async<UnixDatagram>) -> UnixDatagram
fn from(socket: Async<UnixDatagram>) -> UnixDatagram
Performs the conversion.
sourceimpl From<Async<UnixListener>> for UnixListener
impl From<Async<UnixListener>> for UnixListener
sourcefn from(listener: Async<UnixListener>) -> UnixListener
fn from(listener: Async<UnixListener>) -> UnixListener
Performs the conversion.
sourceimpl From<Async<UnixStream>> for UnixStream
impl From<Async<UnixStream>> for UnixStream
sourcefn from(stream: Async<UnixStream>) -> UnixStream
fn from(stream: Async<UnixStream>) -> UnixStream
Performs the conversion.
sourceimpl TryFrom<TcpListener> for Async<TcpListener>
impl TryFrom<TcpListener> for Async<TcpListener>
sourcefn try_from(listener: TcpListener) -> Result<Async<TcpListener>, Error>
fn try_from(listener: TcpListener) -> Result<Async<TcpListener>, Error>
Performs the conversion.
sourceimpl TryFrom<UnixDatagram> for Async<UnixDatagram>
impl TryFrom<UnixDatagram> for Async<UnixDatagram>
sourcefn try_from(socket: UnixDatagram) -> Result<Async<UnixDatagram>, Error>
fn try_from(socket: UnixDatagram) -> Result<Async<UnixDatagram>, Error>
Performs the conversion.
sourceimpl TryFrom<UnixListener> for Async<UnixListener>
impl TryFrom<UnixListener> for Async<UnixListener>
sourcefn try_from(listener: UnixListener) -> Result<Async<UnixListener>, Error>
fn try_from(listener: UnixListener) -> Result<Async<UnixListener>, Error>
Performs the conversion.
sourceimpl TryFrom<UnixStream> for Async<UnixStream>
impl TryFrom<UnixStream> for Async<UnixStream>
sourcefn try_from(stream: UnixStream) -> Result<Async<UnixStream>, Error>
fn try_from(stream: UnixStream) -> Result<Async<UnixStream>, Error>
Performs the conversion.
impl<T> Unpin for Async<T>
Auto Trait Implementations
impl<T> RefUnwindSafe for Async<T> where
T: RefUnwindSafe,
impl<T> Send for Async<T> where
T: Send,
impl<T> Sync for Async<T> where
T: Sync,
impl<T> UnwindSafe for Async<T> where
T: UnwindSafe,
Blanket Implementations
sourceimpl<R> AsyncReadExt for R where
R: AsyncRead + ?Sized,
impl<R> AsyncReadExt for R where
R: AsyncRead + ?Sized,
sourcefn read(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>ⓘNotable traits for ReadFuture<'_, R>impl<'_, R> Future for ReadFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
fn read(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>ⓘNotable traits for ReadFuture<'_, R>impl<'_, R> Future for ReadFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
Reads some bytes from the byte stream. Read more
sourcefn read_vectored(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>]
) -> ReadVectoredFuture<'a, Self>ⓘNotable traits for ReadVectoredFuture<'_, R>impl<'_, R> Future for ReadVectoredFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
fn read_vectored(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>]
) -> ReadVectoredFuture<'a, Self>ⓘNotable traits for ReadVectoredFuture<'_, R>impl<'_, R> Future for ReadVectoredFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
sourcefn read_to_end(
&'a mut self,
buf: &'a mut Vec<u8, Global>
) -> ReadToEndFuture<'a, Self>ⓘNotable traits for ReadToEndFuture<'_, R>impl<'_, R> Future for ReadToEndFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
fn read_to_end(
&'a mut self,
buf: &'a mut Vec<u8, Global>
) -> ReadToEndFuture<'a, Self>ⓘNotable traits for ReadToEndFuture<'_, R>impl<'_, R> Future for ReadToEndFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
sourcefn read_to_string(
&'a mut self,
buf: &'a mut String
) -> ReadToStringFuture<'a, Self>ⓘNotable traits for ReadToStringFuture<'_, R>impl<'_, R> Future for ReadToStringFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
fn read_to_string(
&'a mut self,
buf: &'a mut String
) -> ReadToStringFuture<'a, Self>ⓘNotable traits for ReadToStringFuture<'_, R>impl<'_, R> Future for ReadToStringFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
R: AsyncRead + Unpin + ?Sized, type Output = Result<usize, Error>;
sourcefn read_exact(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>ⓘNotable traits for ReadExactFuture<'_, R>impl<'_, R> Future for ReadExactFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<(), Error>;
where
Self: Unpin,
fn read_exact(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>ⓘNotable traits for ReadExactFuture<'_, R>impl<'_, R> Future for ReadExactFuture<'_, R> where
R: AsyncRead + Unpin + ?Sized, type Output = Result<(), Error>;
where
Self: Unpin,
R: AsyncRead + Unpin + ?Sized, type Output = Result<(), Error>;
Reads the exact number of bytes required to fill buf
. Read more
sourcefn take(self, limit: u64) -> Take<Self>
fn take(self, limit: u64) -> Take<Self>
Creates an adapter which will read at most limit
bytes from it. Read more
sourcefn chain<R>(self, next: R) -> Chain<Self, R> where
R: AsyncRead,
fn chain<R>(self, next: R) -> Chain<Self, R> where
R: AsyncRead,
Creates an adapter which will chain this stream with another. Read more
sourcefn boxed_reader<'a>(self) -> Pin<Box<dyn AsyncRead + Send + 'a, Global>>ⓘNotable traits for Pin<P>impl<P> Future for Pin<P> where
P: DerefMut,
<P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output;
where
Self: 'a + Send,
fn boxed_reader<'a>(self) -> Pin<Box<dyn AsyncRead + Send + 'a, Global>>ⓘNotable traits for Pin<P>impl<P> Future for Pin<P> where
P: DerefMut,
<P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output;
where
Self: 'a + Send,
P: DerefMut,
<P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output;
Boxes the reader and changes its type to dyn AsyncRead + Send + 'a
. Read more
sourceimpl<W> AsyncWriteExt for W where
W: AsyncWrite + ?Sized,
impl<W> AsyncWriteExt for W where
W: AsyncWrite + ?Sized,
sourcefn write(&'a mut self, buf: &'a [u8]) -> WriteFuture<'a, Self>ⓘNotable traits for WriteFuture<'_, W>impl<'_, W> Future for WriteFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
fn write(&'a mut self, buf: &'a [u8]) -> WriteFuture<'a, Self>ⓘNotable traits for WriteFuture<'_, W>impl<'_, W> Future for WriteFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
W: AsyncWrite + Unpin + ?Sized, type Output = Result<usize, Error>;
Writes some bytes into the byte stream. Read more
sourcefn write_vectored(
&'a mut self,
bufs: &'a [IoSlice<'a>]
) -> WriteVectoredFuture<'a, Self>ⓘNotable traits for WriteVectoredFuture<'_, W>impl<'_, W> Future for WriteVectoredFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
fn write_vectored(
&'a mut self,
bufs: &'a [IoSlice<'a>]
) -> WriteVectoredFuture<'a, Self>ⓘNotable traits for WriteVectoredFuture<'_, W>impl<'_, W> Future for WriteVectoredFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<usize, Error>;
where
Self: Unpin,
W: AsyncWrite + Unpin + ?Sized, type Output = Result<usize, Error>;
sourcefn write_all(&'a mut self, buf: &'a [u8]) -> WriteAllFuture<'a, Self>ⓘNotable traits for WriteAllFuture<'_, W>impl<'_, W> Future for WriteAllFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<(), Error>;
where
Self: Unpin,
fn write_all(&'a mut self, buf: &'a [u8]) -> WriteAllFuture<'a, Self>ⓘNotable traits for WriteAllFuture<'_, W>impl<'_, W> Future for WriteAllFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<(), Error>;
where
Self: Unpin,
W: AsyncWrite + Unpin + ?Sized, type Output = Result<(), Error>;
Writes an entire buffer into the byte stream. Read more
sourcefn flush(&mut self) -> FlushFuture<'_, Self>ⓘNotable traits for FlushFuture<'_, W>impl<'_, W> Future for FlushFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<(), Error>;
where
Self: Unpin,
fn flush(&mut self) -> FlushFuture<'_, Self>ⓘNotable traits for FlushFuture<'_, W>impl<'_, W> Future for FlushFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<(), Error>;
where
Self: Unpin,
W: AsyncWrite + Unpin + ?Sized, type Output = Result<(), Error>;
Flushes the stream to ensure that all buffered contents reach their destination. Read more
sourcefn close(&mut self) -> CloseFuture<'_, Self>ⓘNotable traits for CloseFuture<'_, W>impl<'_, W> Future for CloseFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<(), Error>;
where
Self: Unpin,
fn close(&mut self) -> CloseFuture<'_, Self>ⓘNotable traits for CloseFuture<'_, W>impl<'_, W> Future for CloseFuture<'_, W> where
W: AsyncWrite + Unpin + ?Sized, type Output = Result<(), Error>;
where
Self: Unpin,
W: AsyncWrite + Unpin + ?Sized, type Output = Result<(), Error>;
Closes the writer. Read more
sourcefn boxed_writer<'a>(self) -> Pin<Box<dyn AsyncWrite + Send + 'a, Global>>ⓘNotable traits for Pin<P>impl<P> Future for Pin<P> where
P: DerefMut,
<P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output;
where
Self: 'a + Send,
fn boxed_writer<'a>(self) -> Pin<Box<dyn AsyncWrite + Send + 'a, Global>>ⓘNotable traits for Pin<P>impl<P> Future for Pin<P> where
P: DerefMut,
<P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output;
where
Self: 'a + Send,
P: DerefMut,
<P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output;
Boxes the writer and changes its type to dyn AsyncWrite + Send + 'a
. Read more
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more