Function in io::net::tcp compiler

listen

fn listen(string host, int port) -> Result<Stream, IoError>
Import
use io::net::tcp::{listen};
Source: compiler/src/builtin_docs/io/net/tcp.hy

Opens a TCP socket listening on host and port.

port may be 0 to let the OS pick a free port; read it back with local_addr. A host name is resolved and only the first address is used, so prefer an explicit IP such as "127.0.0.1" or "0.0.0.0". Take connections with accept (or io::sync::accept_wait).

Returns Err(IoError::InvalidInput) for a port outside 0..=65535; an address already in use is reported as an OS error. A program that reaches listen compiles only with --allow-net.

Parameters#

NameType
hoststring
portint

Returns#

Result<Stream, IoError>

Examples#

use io::{IoError};
use io::net::tcp::{connect, listen, local_addr};
use io::sync::{accept_wait, read_to_end, write_all};
use io::net::tcp::{shutdown};
use string::{from_bytes, to_bytes};
use tests::assert;
fn run() -> Result<string, IoError> {
    let listener = listen("127.0.0.1", 0)?;
    let (_, port) = local_addr(listener)?;
    let client = connect("127.0.0.1", port)?;
    let server = accept_wait(listener)?;
    write_all(client, to_bytes("hello"))?;
    shutdown(client, 1)?;
    return from_bytes(read_to_end(server)?)?;
}

fn main() {
    let got = match run() {
        Result::Ok(s) => s,
        Result::Err(_) => "",
    };
    assert!(got == "hello");
}

See also#

↑ ↓ navigate ↵ open