Qu

tcp_send

Builtin index · Concurrency

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.

CodeInputOutputDescription
result = tcp_send(sock, data), tcp_recv(sock, [max_bytes=4096])
sock TcpConn or stringnot documented yet
data 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)
output
hello

from concurrency

How it works

tcp_send(conn, data) writes data's UTF-8 bytes to the connection, no added newline or framing — as bare as write(f, s) above. A script that needs message boundaries adds its own (a trailing delimiter, a length prefix, ...).

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

See also

tcp_recv — documented in the same entry.