Struct std::io::net::tcp::TcpListener[src]

pub struct TcpListener {
    // some fields omitted
}

A structure representing a socket server. This listener is used to create a TcpAcceptor which can be used to accept sockets on a local port.

Example

fn main() { } fn foo() { #![allow(dead_code)] use std::io::{TcpListener, TcpStream}; use std::io::{Acceptor, Listener}; let listener = TcpListener::bind("127.0.0.1", 80); // bind the listener to the specified address let mut acceptor = listener.listen(); fn handle_client(mut stream: TcpStream) { // ... &mut stream; // silence unused mutability/variable warning } // accept connections and process them, spawning a new tasks for each one for stream in acceptor.incoming() { match stream { Err(e) => { /* connection failed */ } Ok(stream) => spawn(proc() { // connection succeeded handle_client(stream) }) } } // close the socket server drop(acceptor); }
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};

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

// bind the listener to the specified address
let mut acceptor = listener.listen();

fn handle_client(mut stream: TcpStream) {
    // ...
}
// accept connections and process them, spawning a new tasks for each one
for stream in acceptor.incoming() {
    match stream {
        Err(e) => { /* connection failed */ }
        Ok(stream) => spawn(proc() {
            // connection succeeded
            handle_client(stream)
        })
    }
}

// close the socket server
drop(acceptor);

Methods

impl TcpListener

fn bind(addr: &str, port: u16) -> IoResult<TcpListener>

Creates a new TcpListener which will be bound to the specified IP and port. This listener is not ready for accepting connections, listen must be called on it before that's possible.

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 socket_name function.

fn socket_name(&mut self) -> IoResult<SocketAddr>

Returns the local socket address of this listener.

Trait Implementations

impl Listener<TcpStream, TcpAcceptor> for TcpListener

fn listen(self) -> IoResult<TcpAcceptor>