Struct compio_net::TcpListener
source · pub struct TcpListener { /* private fields */ }
Expand description
A TCP socket server, listening for connections.
You can accept a new connection by using the
accept
method.
Examples
use std::net::SocketAddr;
use compio_net::{TcpListener, TcpStream};
use socket2::SockAddr;
let addr: SockAddr = "127.0.0.1:2345".parse::<SocketAddr>().unwrap().into();
let listener = TcpListener::bind(&addr).unwrap();
compio_runtime::block_on(async move {
let tx_fut = TcpStream::connect(&addr);
let rx_fut = listener.accept();
let (tx, (rx, _)) = futures_util::try_join!(tx_fut, rx_fut).unwrap();
tx.send_all("test").await.0.unwrap();
let (_, buf) = rx.recv_exact(Vec::with_capacity(4)).await.unwrap();
assert_eq!(buf, b"test");
});
Implementations§
source§impl TcpListener
impl TcpListener
sourcepub fn bind(addr: impl ToSockAddrs) -> Result<Self>
pub fn bind(addr: impl ToSockAddrs) -> Result<Self>
Creates a new TcpListener
, which will be bound to the specified
address.
The returned listener is ready for accepting connections.
Binding with a port number of 0 will request that the OS assigns a port to this listener.
sourcepub fn try_clone(&self) -> Result<Self>
pub fn try_clone(&self) -> Result<Self>
Creates a new independently owned handle to the underlying socket.
It does not clear the attach state.
sourcepub async fn accept(&self) -> Result<(TcpStream, SockAddr)>
pub async fn accept(&self) -> Result<(TcpStream, SockAddr)>
Accepts a new incoming connection from this listener.
This function will yield once a new TCP connection is established. When
established, the corresponding TcpStream
and the remote peer’s
address will be returned.
sourcepub fn local_addr(&self) -> Result<SockAddr>
pub fn local_addr(&self) -> Result<SockAddr>
Returns the local address that this listener is bound to.
This can be useful, for example, when binding to port 0 to figure out which port was actually bound.
Examples
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use compio_net::TcpListener;
use socket2::SockAddr;
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
let addr = listener.local_addr().expect("Couldn't get local address");
assert_eq!(
addr.as_socket().unwrap(),
SocketAddr::from(SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::new(127, 0, 0, 1),
8080
)))
);
Trait Implementations§
source§impl AsRawFd for TcpListener
impl AsRawFd for TcpListener
source§impl FromRawFd for TcpListener
impl FromRawFd for TcpListener
source§unsafe fn from_raw_fd(fd: RawFd) -> Self
unsafe fn from_raw_fd(fd: RawFd) -> Self
Self
from the given raw file
descriptor. Read more