[go: up one dir, main page]

Struct TcpListener

Source
pub struct TcpListener { /* private fields */ }
Expand description

A TCP socket server, listening for connections.

After creating a TcpListener by binding it to a socket address, it listens for incoming TCP connections. These can be accepted by awaiting elements from the async stream of incoming connections, incoming.

The socket will be closed when the value is dropped.

§Examples

use std::error::Error;

use romio::tcp::{TcpListener, TcpStream};
use futures::prelude::*;

async fn recite_shakespeare(mut stream: TcpStream) {
    stream.write_all(b"Shall I hear more, or shall I speak at this?").await;
}

async fn listen() -> Result<(), Box<dyn Error + 'static>> {
    let socket_addr = "127.0.0.1:80".parse()?;
    let mut listener = TcpListener::bind(&socket_addr)?;
    let mut incoming = listener.incoming();

    // accept connections and process them serially
    while let Some(stream) = incoming.next().await {
        recite_shakespeare(stream?).await;
    }
    Ok(())
}

Implementations§

Source§

impl TcpListener

Source

pub fn bind(addr: &SocketAddr) -> Result<TcpListener>

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. The port allocated can be queried via the local_addr method.

§Examples

Create a TCP listener bound to 127.0.0.1:80:

use romio::tcp::TcpListener;

let socket_addr = "127.0.0.1:80".parse()?;
let listener = TcpListener::bind(&socket_addr)?;
Source

pub fn local_addr(&self) -> Result<SocketAddr>

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 romio::tcp::TcpListener;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

let socket_addr = "127.0.0.1:8080".parse()?;
let listener = TcpListener::bind(&socket_addr)?;

let expected = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
assert_eq!(listener.local_addr()?, SocketAddr::V4(expected));
Source

pub fn incoming(&mut self) -> Incoming<'_>

Consumes this listener, returning a stream of the sockets this listener accepts.

This method returns an implementation of the Stream trait which resolves to the sockets the are accepted on this listener.

§Errors

Note that accepting a connection can lead to various errors and not all of them are necessarily fatal ‒ for example having too many open file descriptors or the other side closing the connection while it waits in an accept queue. These would terminate the stream if not handled in any way.

§Examples
use futures::prelude::*;
use romio::tcp::TcpListener;

let socket_addr = "127.0.0.1:80".parse()?;
let mut listener = TcpListener::bind(&socket_addr)?;
let mut incoming = listener.incoming();

// accept connections and process them serially
while let Some(stream) = incoming.next().await {
    match stream {
        Ok(stream) => {
            println!("new client!");
        },
        Err(e) => { /* connection failed */ }
    }
}
Source

pub fn ttl(&self) -> Result<u32>

Gets the value of the IP_TTL option for this socket.

For more information about this option, see set_ttl.

§Examples
use futures::prelude::*;
use romio::tcp::TcpListener;

let socket_addr = "127.0.0.1:0".parse()?;
let listener = TcpListener::bind(&socket_addr)?;
listener.set_ttl(100)?;
assert_eq!(listener.ttl()?, 100);
Source

pub fn set_ttl(&self, ttl: u32) -> Result<()>

Sets the value for the IP_TTL option on this socket.

This value sets the time-to-live field that is used in every packet sent from this socket.

§Examples
use futures::prelude::*;
use romio::tcp::TcpListener;

let socket_addr = "127.0.0.1:0".parse()?;
let listener = TcpListener::bind(&socket_addr)?;
listener.set_ttl(100)?;

Trait Implementations§

Source§

impl AsRawFd for TcpListener

Source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
Source§

impl AsyncReady for TcpListener

Source§

fn poll_ready( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<Self::Ok, Self::Err>>

Check if the stream can be read from.

Source§

type Ok = (TcpStream, SocketAddr)

The type of successful values yielded by this trait.
Source§

type Err = Error

The type of failures yielded by this trait.
Source§

fn poll_ready_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<Self::Ok, Self::Err>>
where Self: Sized + Unpin,

A convenience for calling AsyncReady::poll_ready on Unpin types.
Source§

impl Debug for TcpListener

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.