Struct kvarn::prelude::utils::prelude::net::TcpListener

1.0.0 · source ·
pub struct TcpListener(_);
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 calling accept or by iterating over the Incoming iterator returned by incoming.

The socket will be closed when the value is dropped.

The Transmission Control Protocol is specified in IETF RFC 793.

Examples

use std::net::{TcpListener, TcpStream};

fn handle_client(stream: TcpStream) {
    // ...
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:80")?;

    // accept connections and process them serially
    for stream in listener.incoming() {
        handle_client(stream?);
    }
    Ok(())
}

Implementations§

source§

impl TcpListener

source

pub fn bind<A>(addr: A) -> Result<TcpListener, Error>where A: ToSocketAddrs,

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 TcpListener::local_addr method.

The address type can be any implementor of ToSocketAddrs trait. See its documentation for concrete examples.

If addr yields multiple addresses, bind will be attempted with each of the addresses until one succeeds and returns the listener. If none of the addresses succeed in creating a listener, the error returned from the last attempt (the last address) is returned.

Examples

Creates a TCP listener bound to 127.0.0.1:80:

use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:80").unwrap();

Creates a TCP listener bound to 127.0.0.1:80. If that fails, create a TCP listener bound to 127.0.0.1:443:

use std::net::{SocketAddr, TcpListener};

let addrs = [
    SocketAddr::from(([127, 0, 0, 1], 80)),
    SocketAddr::from(([127, 0, 0, 1], 443)),
];
let listener = TcpListener::bind(&addrs[..]).unwrap();
source

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

Returns the local socket address of this listener.

Examples
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};

let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
assert_eq!(listener.local_addr().unwrap(),
           SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
source

pub fn try_clone(&self) -> Result<TcpListener, Error>

Creates a new independently owned handle to the underlying socket.

The returned TcpListener is a reference to the same socket that this object references. Both handles can be used to accept incoming connections and options set on one listener will affect the other.

Examples
use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
let listener_clone = listener.try_clone().unwrap();
source

pub fn accept(&self) -> Result<(TcpStream, SocketAddr), Error>

Accept a new incoming connection from this listener.

This function will block the calling thread until a new TCP connection is established. When established, the corresponding TcpStream and the remote peer’s address will be returned.

Examples
use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
match listener.accept() {
    Ok((_socket, addr)) => println!("new client: {addr:?}"),
    Err(e) => println!("couldn't get client: {e:?}"),
}
source

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

Returns an iterator over the connections being received on this listener.

The returned iterator will never return None and will also not yield the peer’s SocketAddr structure. Iterating over it is equivalent to calling TcpListener::accept in a loop.

Examples
use std::net::{TcpListener, TcpStream};

fn handle_connection(stream: TcpStream) {
   //...
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:80")?;

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                handle_connection(stream);
            }
            Err(e) => { /* connection failed */ }
        }
    }
    Ok(())
}
source

pub fn into_incoming(self) -> IntoIncoming

🔬This is a nightly-only experimental API. (tcplistener_into_incoming)

Turn this into an iterator over the connections being received on this listener.

The returned iterator will never return None and will also not yield the peer’s SocketAddr structure. Iterating over it is equivalent to calling TcpListener::accept in a loop.

Examples
#![feature(tcplistener_into_incoming)]
use std::net::{TcpListener, TcpStream};

fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
    let listener = TcpListener::bind("127.0.0.1:80").unwrap();
    listener.into_incoming()
        .filter_map(Result::ok) /* Ignore failed connections */
}

fn main() -> std::io::Result<()> {
    for stream in listen_on(80) {
        /* handle the connection here */
    }
    Ok(())
}
1.9.0 · source

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

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 std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:80").unwrap();
listener.set_ttl(100).expect("could not set TTL");
1.9.0 · source

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

Gets the value of the IP_TTL option for this socket.

For more information about this option, see TcpListener::set_ttl.

Examples
use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:80").unwrap();
listener.set_ttl(100).expect("could not set TTL");
assert_eq!(listener.ttl().unwrap_or(0), 100);
1.9.0 · source

pub fn set_only_v6(&self, only_v6: bool) -> Result<(), Error>

👎Deprecated since 1.16.0: this option can only be set before the socket is bound
1.9.0 · source

pub fn only_v6(&self) -> Result<bool, Error>

👎Deprecated since 1.16.0: this option can only be set before the socket is bound
1.9.0 · source

pub fn take_error(&self) -> Result<Option<Error>, Error>

Gets the value of the SO_ERROR option on this socket.

This will retrieve the stored error in the underlying socket, clearing the field in the process. This can be useful for checking errors between calls.

Examples
use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:80").unwrap();
listener.take_error().expect("No error was expected");
1.9.0 · source

pub fn set_nonblocking(&self, nonblocking: bool) -> Result<(), Error>

Moves this TCP stream into or out of nonblocking mode.

This will result in the accept operation becoming nonblocking, i.e., immediately returning from their calls. If the IO operation is successful, Ok is returned and no further action is required. If the IO operation could not be completed and needs to be retried, an error with kind io::ErrorKind::WouldBlock is returned.

On Unix platforms, calling this method corresponds to calling fcntl FIONBIO. On Windows calling this method corresponds to calling ioctlsocket FIONBIO.

Examples

Bind a TCP listener to an address, listen for connections, and read bytes in nonblocking mode:

use std::io;
use std::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
listener.set_nonblocking(true).expect("Cannot set non-blocking");

for stream in listener.incoming() {
    match stream {
        Ok(s) => {
            // do something with the TcpStream
            handle_connection(s);
        }
        Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
            // wait until network socket is ready, typically implemented
            // via platform-specific APIs such as epoll or IOCP
            wait_for_fd();
            continue;
        }
        Err(e) => panic!("encountered IO error: {e}"),
    }
}

Trait Implementations§

1.63.0 · source§

impl AsFd for TcpListener

source§

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
source§

impl AsRawFd for TcpListener

source§

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
source§

impl Debug for TcpListener

source§

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

Formats the value using the given formatter. Read more
1.63.0 · source§

impl From<OwnedFd> for TcpListener

source§

fn from(owned_fd: OwnedFd) -> TcpListener

Converts to this type from the input type.
source§

impl From<Socket> for TcpListener

source§

fn from(socket: Socket) -> TcpListener

Converts to this type from the input type.
§

impl From<Socket> for TcpListener

§

fn from(socket: Socket) -> TcpListener

Converts to this type from the input type.
1.63.0 · source§

impl From<TcpListener> for OwnedFd

source§

fn from(tcp_listener: TcpListener) -> OwnedFd

Converts to this type from the input type.
source§

impl From<TcpListener> for Socket

source§

fn from(socket: TcpListener) -> Socket

Converts to this type from the input type.
§

impl From<TcpListener> for Socket

§

fn from(socket: TcpListener) -> Socket

Converts to this type from the input type.
1.1.0 · source§

impl FromRawFd for TcpListener

source§

unsafe fn from_raw_fd(fd: i32) -> TcpListener

Constructs a new instance of Self from the given raw file descriptor. Read more
1.4.0 · source§

impl IntoRawFd for TcpListener

source§

fn into_raw_fd(self) -> i32

Consumes this object, returning the raw underlying file descriptor. Read more
§

impl TryFrom<TcpListener> for TcpListener

§

fn try_from( stream: TcpListener ) -> Result<TcpListener, <TcpListener as TryFrom<TcpListener>>::Error>

Consumes stream, returning the tokio I/O object.

This is equivalent to TcpListener::from_std(stream).

§

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32 ) -> TaggedParser<'a, Implicit, Self, E>

source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

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

const: unstable · 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.

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

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

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more