cancellable_io

Struct TcpListener

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

A TCP socket server, listening for connections.

The socket will be closed when the value is dropped.

The accept and the incoming methods can be interrupted using the Canceller object created with the socket.

Otherwise similar to std::net::TcpListener.

Implementations§

Source§

impl TcpListener

Source

pub fn bind<A: ToSocketAddrs>(address: A) -> Result<(Self, Canceller)>

Creates a new TcpListener which will be bound to the specified address, together with an object that allows cancelling accept operations.

Examples found in repository?
examples/example1.rs (line 8)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
fn main() {
    let (listener, listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap();
    let address = listener.local_addr().unwrap();
    let server = thread::spawn(move || {
        println!("Server: ready");
        let (mut socket, socket_canceller, addr) = listener.accept().unwrap();
        println!("Server: got connection from {}", addr);

        let connection = thread::spawn(move || {
            println!("Connection: ready");
            let mut buf = [0; 16];
            let len = socket.read(&mut buf).unwrap();
            println!("Connection: read {}", String::from_utf8_lossy(&buf[..len]));
            println!("Connection: try reading more.");
            match socket.read(&mut buf) {
                Ok(0) => println!("Connection: socket closed."),
                Err(ref e) if is_cancelled(e) => println!("Connection: cancelled."),
                ref e => panic!("Connection: unexpected {:?}", e),
            }
        });

        println!("Server: try accepting more.");
        if is_cancelled(&listener.accept().unwrap_err()) {
            println!("Server: accept cancelled.");
        }

        socket_canceller.cancel().unwrap();
        connection.join().unwrap();
    });

    thread::sleep(Duration::from_secs(2));
    let (mut socket, socket_canceller) = TcpStream::connect(&address).unwrap();
    let client = thread::spawn(move || {
        println!("Client: ready");
        thread::sleep(Duration::from_secs(2));
        println!("Client: write data.");
        socket.write(b"Hello!").unwrap();
        println!("Client: try reading.");
        let mut buf = [0; 16];
        match socket.read(&mut buf) {
            Ok(0) => println!("Client: socket closed."),
            Err(ref e) if is_cancelled(e) => println!("Client: cancelled."),
            ref e => panic!("Client: unexpected {:?}", e),
        }
    });

    thread::sleep(Duration::from_secs(4));
    socket_canceller.cancel().unwrap();
    thread::sleep(Duration::from_secs(2));
    listener_canceller.cancel().unwrap();

    server.join().unwrap();
    client.join().unwrap();
}
Source

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

Returns the local socket address of this listener.

Examples found in repository?
examples/example1.rs (line 9)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
fn main() {
    let (listener, listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap();
    let address = listener.local_addr().unwrap();
    let server = thread::spawn(move || {
        println!("Server: ready");
        let (mut socket, socket_canceller, addr) = listener.accept().unwrap();
        println!("Server: got connection from {}", addr);

        let connection = thread::spawn(move || {
            println!("Connection: ready");
            let mut buf = [0; 16];
            let len = socket.read(&mut buf).unwrap();
            println!("Connection: read {}", String::from_utf8_lossy(&buf[..len]));
            println!("Connection: try reading more.");
            match socket.read(&mut buf) {
                Ok(0) => println!("Connection: socket closed."),
                Err(ref e) if is_cancelled(e) => println!("Connection: cancelled."),
                ref e => panic!("Connection: unexpected {:?}", e),
            }
        });

        println!("Server: try accepting more.");
        if is_cancelled(&listener.accept().unwrap_err()) {
            println!("Server: accept cancelled.");
        }

        socket_canceller.cancel().unwrap();
        connection.join().unwrap();
    });

    thread::sleep(Duration::from_secs(2));
    let (mut socket, socket_canceller) = TcpStream::connect(&address).unwrap();
    let client = thread::spawn(move || {
        println!("Client: ready");
        thread::sleep(Duration::from_secs(2));
        println!("Client: write data.");
        socket.write(b"Hello!").unwrap();
        println!("Client: try reading.");
        let mut buf = [0; 16];
        match socket.read(&mut buf) {
            Ok(0) => println!("Client: socket closed."),
            Err(ref e) if is_cancelled(e) => println!("Client: cancelled."),
            ref e => panic!("Client: unexpected {:?}", e),
        }
    });

    thread::sleep(Duration::from_secs(4));
    socket_canceller.cancel().unwrap();
    thread::sleep(Duration::from_secs(2));
    listener_canceller.cancel().unwrap();

    server.join().unwrap();
    client.join().unwrap();
}
Source

pub fn try_clone(&self) -> Result<(Self, Canceller)>

Creates a new independently owned handle to the underlying socket.

Source

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

Accepts a new incoming connection from this listener.

This method can be cancelled by the associated Canceller object.

This method returns a TcpStream with an associated Canceller and the address of the remote peer.

Examples found in repository?
examples/example1.rs (line 12)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
fn main() {
    let (listener, listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap();
    let address = listener.local_addr().unwrap();
    let server = thread::spawn(move || {
        println!("Server: ready");
        let (mut socket, socket_canceller, addr) = listener.accept().unwrap();
        println!("Server: got connection from {}", addr);

        let connection = thread::spawn(move || {
            println!("Connection: ready");
            let mut buf = [0; 16];
            let len = socket.read(&mut buf).unwrap();
            println!("Connection: read {}", String::from_utf8_lossy(&buf[..len]));
            println!("Connection: try reading more.");
            match socket.read(&mut buf) {
                Ok(0) => println!("Connection: socket closed."),
                Err(ref e) if is_cancelled(e) => println!("Connection: cancelled."),
                ref e => panic!("Connection: unexpected {:?}", e),
            }
        });

        println!("Server: try accepting more.");
        if is_cancelled(&listener.accept().unwrap_err()) {
            println!("Server: accept cancelled.");
        }

        socket_canceller.cancel().unwrap();
        connection.join().unwrap();
    });

    thread::sleep(Duration::from_secs(2));
    let (mut socket, socket_canceller) = TcpStream::connect(&address).unwrap();
    let client = thread::spawn(move || {
        println!("Client: ready");
        thread::sleep(Duration::from_secs(2));
        println!("Client: write data.");
        socket.write(b"Hello!").unwrap();
        println!("Client: try reading.");
        let mut buf = [0; 16];
        match socket.read(&mut buf) {
            Ok(0) => println!("Client: socket closed."),
            Err(ref e) if is_cancelled(e) => println!("Client: cancelled."),
            ref e => panic!("Client: unexpected {:?}", e),
        }
    });

    thread::sleep(Duration::from_secs(4));
    socket_canceller.cancel().unwrap();
    thread::sleep(Duration::from_secs(2));
    listener_canceller.cancel().unwrap();

    server.join().unwrap();
    client.join().unwrap();
}
Source

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

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

The iteration can be cancelled by the associated Canceller object. If the iteration is cancelled, the next() method will return an error that can be identified with is_cancelled.

Source

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

Sets the value for the IP_TTL option on this socket.

Source

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

Gets the value for the IP_TTL option for this socket.

Source

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

Gets the value for the SO_ERROR option for this socket.

Source

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

Moves this TCP connection into or out of non blocking mode.

Trait Implementations§

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.