tcp_accept
result =tcp_listen(port),tcp_accept(listener)
Input: port · Output: result
What it is
tcp_listen(port): port (integer 0-65535, 0 asks the OS for a free ephemeral port) binds and returns a TcpListener handle immediately (does not block). tcp_accept(listener): takes that handle and blocks the calling thread until a client connects, then returns a TcpConn handle for the new connection — call it in a loop to accept multiple clients, one call per connection.
Overloads
One call shape — this function is not overloaded.
| Code | Input | Output | Description |
result = tcp_listen(port), tcp_accept(listener) | port TcpListener or TcpConnnot documented yet | result TcpListener or TcpConn | Returns a TcpListener handle from tcp_listen, and a TcpConn handle from tcp_accept. |
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)
hello
from concurrency
How it works
tcp_accept(listener) blocks until a client connects, then returns the new connection as a Value::TcpConn. Call this in a loop inside a spawn'd server function to accept multiple clients, one call per connection.
From the note above this builtin in the interpreter, where the reasoning was written down as it was built.
See also
tcp_listen — documented in the same entry.