tcp_recv
result =tcp_send(sock, data),tcp_recv(sock, [max_bytes=4096])
Input: sock, data · Output: result
What it is
tcp_send: sock (a TcpConn handle) and data (string, written as UTF-8 bytes) — returns none. tcp_recv: sock (a TcpConn handle) and an optional integer kwarg max_bytes (default 4096) — blocks until at least one byte arrives, reads up to max_bytes, and returns it as a string (UTF-8, decoded lossily), or none if the peer closed the connection (a zero-byte read). Neither call frames the message for you — TCP is a stream, so a length prefix or delimiter is yours to add if you need distinct messages.
Overloads
One call shape — this function is not overloaded.
| Code | Input | Output | Description |
result = tcp_send(sock, data), tcp_recv(sock, [max_bytes=4096]) | sock TcpConn or stringnot documented yetdata TcpConn or stringnot documented yet | result Str | Returns a Str of the bytes read from tcp_recv, or none once the peer has closed; tcp_send hands back no value. |
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_recv(conn, [max_bytes=]) blocks until at least one byte arrives, reads up to max_bytes (default 4096) and returns it decoded as UTF-8 (lossy — matching read_all's own text-mode decoding; guaranteed binary-safe transfer is a real follow-up, not attempted here). Returns Value::Nothing at EOF (the peer closed its write side, a 0-byte read) — the same "absent" marker read_line returns at file EOF.
From the note above this builtin in the interpreter, where the reasoning was written down as it was built.
See also
tcp_send — documented in the same entry.