lev.tcp

lev

tcp() -> socket, err

Create a non-blocking TCP socket

Returns a wrapped TCP socket that integrates with the event loop. Provides send, recv, recv_exactly, recv_until methods with async I/O via wait_readable/wait_writable. Supports TLS upgrade via starttls. One task may read while another writes: each direction holds its own waiter on the socket. Until a TLS handshake is done, send and recv from another task return nil, "not connected".

On a TLS client socket past its handshake, peer_key_hash returns the SHA-256 of the SubjectPublicKeyInfo of the server's certificate, as 32 raw bytes. It reads the same with verify = false, so a caller can pin a server's key or trust it on first use.

getsockname returns the socket's own addr, port, and getpeername the far end's. On an AF_UNIX socket both return nil, "not an IP socket". getpeercred returns the peer's pid, uid, gid on a connected AF_UNIX socket, and nil, "not a unix socket" on a TCP socket.

send(data, opts) takes two limits. opts.timeout is the deadline for the whole call: 30 seconds when nil, none when false. opts.stall ends the send with "timeout" once the socket has taken nothing for that many seconds. A send that fails returns nil, err, sent, where sent counts the bytes the socket took. After a timeout or a cancel the stream is whole, and send(data:sub(sent + 1)) resumes it. Under TLS sent counts bytes sealed into records, and the last record may wait in the socket: the next send writes it first, an empty one included.

recv(maxlen) reads up to 4096 bytes when maxlen is nil or at or below zero. recv_exactly(0) returns "", and a negative n returns nil, "invalid length". A recv_exactly that fails keeps the bytes it read for the next read. recv_until answers nil, "max_size exceeded" when its match ends past max_size (65536 when nil), and keeps the bytes.