Struct std::io::net::tcp::TcpListenerExperimental
[-]
[+]
[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}; use std::thread::Thread; 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) => Thread::spawn(move|| { // connection succeeded handle_client(stream) }).detach() } } // close the socket server drop(acceptor); }use std::io::{TcpListener, TcpStream}; use std::io::{Acceptor, Listener}; use std::thread::Thread; 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) => Thread::spawn(move|| { // connection succeeded handle_client(stream) }).detach() } } // close the socket server drop(acceptor);
Methods
impl TcpListener
fn bind<A: ToSocketAddr>(addr: A) -> IoResult<TcpListener>
Creates a new TcpListener
which will be bound to the specified address.
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.
The address type can be any implementer of ToSocketAddr
trait. See its
documentation for concrete examples.
fn socket_name(&mut self) -> IoResult<SocketAddr>
Returns the local socket address of this listener.