Struct lunatic::net::TcpListener[][src]

pub struct TcpListener { /* fields omitted */ }
Expand description

A TCP server, listening for connections.

After creating a TcpListener by binding it to an address, it listens for incoming TCP connections. These can be accepted by calling accept().

The Transmission Control Protocol is specified in IETF RFC 793.

Examples

use lunatic::{net, process, Mailbox};
use std::io::{BufRead, BufReader, Write};

fn main() {
    let listener = net::TcpListener::bind("127.0.0.1:1337").unwrap();
    while let Ok((tcp_stream, _peer)) = listener.accept() {
        // Handle connections in a new process
        process::spawn_with(tcp_stream, handle).unwrap();
    }
}

fn handle(mut tcp_stream: net::TcpStream, _: Mailbox<()>) {
    let mut buf_reader = BufReader::new(tcp_stream.clone());
    loop {
        let mut buffer = String::new();
        let read = buf_reader.read_line(&mut buffer).unwrap();
        if buffer.contains("exit") || read == 0 {
            return;
        }
        tcp_stream.write(buffer.as_bytes()).unwrap();
    }
}

Implementations

Creates a new TcpListener bound to the given address.

Binding with a port number of 0 will request that the operating system assigns an available port to this listener.

If addr yields multiple addresses, binding 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 from the last attempt is returned.

Accepts a new incoming connection.

Returns a TCP stream and the peer address.

Trait Implementations

Formats the value using the given formatter. Read more

Executes the destructor for this type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.