Qu

tcp_port

Builtin index · Concurrency

result = tcp_connect(host, port), tcp_port(listener)

Input: host, port · Output: result

What it is

tcp_connect(host, port): host (string, hostname or IP) and port (integer 0-65535) — blocks until connected (or the OS gives up and errors), returning a TcpConn handle, the client-side mirror of tcp_accept. tcp_port(listener): takes a TcpListener handle and returns an integer, the port it actually bound — which matters when you asked for 0 and let the system choose.

Overloads

One call shape — this function is not overloaded.

CodeInputOutputDescription
result = tcp_connect(host, port), tcp_port(listener)
host string or TcpConnnot documented yet
port string or TcpConnnot documented yet
result TcpConn, scalar, or Num
Returns a TcpConn handle from tcp_connect, and the bound port as a scalar Num from tcp_port.

Examples

From the documentation, and run by the build -- the output and the figure below are what the engine actually produced. Simplest first.

function echo_once(listener)
    conn = tcp_accept(listener)        # blocks for the one client

    msg = tcp_recv(conn)
    tcp_send(conn, msg)
    tcp_close(conn)
end function

listener = tcp_listen(0)               # 0 -- let the OS pick a free port

port = tcp_port(listener)
w = spawn("echo_once", listener)

client = tcp_connect("127.0.0.1", port)
tcp_send(client, "hello")
print(tcp_recv(client))                # "hello" -- echoed back

tcp_close(client)
join(w)
output
hello

from concurrency

How it works

tcp_port(listener) — the actual bound port, needed after tcp_listen(0) (ask the OS for any free ephemeral port, avoiding a fixed port a real test or a second concurrent instance of a script could collide on) to find out which port the OS actually picked, so a client elsewhere can be told where to connect.

From the note above this builtin in the interpreter, where the reasoning was written down as it was built.

See also

tcp_connect — documented in the same entry.