Skip to main content

coloX Net Networking Module Lua Programming Guide

The coloX networking module provides TCP/UDP/Multicast sockets, the Copas asynchronous I/O scheduler, an HTTP client, URL parsing, and LTN12 streams for embedded networking and HTTP API calls.

Enabling the Module​

Enable net with usemod('net'); true indicates success.

usemod('net')

The following global functions and socket objects are then available. Copas and the HTTP client require additional Lua scripts loaded with #include (below).


Contents​

  1. Architecture
  2. Global functions
  3. Socket methods
  4. Copas asynchronous scheduler
  5. HTTP client (nethttp)
  6. WebSocket client (ws)
  7. URL parsing (nethttp)
  8. LTN12 streams
  9. Complete examples
  10. Complete API index

1. Architecture​

The coloX networking module has three layers:

┌─────────────────────────────────────────────┐
│ Application: nethttp.request() │ HTTP requests
├─────────────────────────────────────────────┤
│ Scheduler: copas.step() / copas.addthread() │ Coroutine-based asynchronous I/O
├─────────────────────────────────────────────┤
│ Transport: net_bind / net_connect / socket │ TCP/UDP/Multicast
└─────────────────────────────────────────────┘
  • Transport — Native host implementation providing nonblocking socket operations
  • Scheduling — Pure Lua (colox_net.lua), coroutine-based cooperative multitasking
  • Application — Pure Lua (colox_http.lua), HTTP/1.1 client; colox_ws.lua implements a WebSocket client over Copas

Key Features​

  • All sockets are nonblocking by default—socket reads/writes do not block the frame loop; however, DNS resolution is synchronous and blocking (cold caches may stall for milliseconds). Direct IP connections avoid this
  • No select timeout—net_select uses a fixed timeout of 0 and returns immediately
  • Coroutine-driven—call copas.step() in each frame's _draw() to drive all network I/O
  • Timeout detection and disconnection cleanup—built into Copas (no automatic reconnection; implement it yourself)

2. Global Functions​

net_bind([type], [addr], port [, backlog]) → socket | nil, err​

Creates a server socket, binds the port, and begins listening.

Parameters:

ParameterTypeDefaultDescription
typestring"tcp"Socket type: "tcp", "udp", "mcast"
addrstring"0.0.0.0"Bind address; nil binds all interfaces
portnumberRequiredPort number
backlognumber2TCP listen queue length

Returns:

  • Success: socket object
  • Failure: nil, error string

Example:

-- TCP server (listen on port 8080 on all interfaces)
local server, err = net_bind("tcp", 8080)
-- Equivalent to
local server, err = net_bind("tcp", nil, 8080, 2)

-- UDP server (bind to a specific address)
local server, err = net_bind("udp", "192.168.1.100", 9000)

-- Multicast
local server, err = net_bind("mcast", "239.255.0.1", 5000)

Notes:

  • TCP sockets call listen() automatically; use accept() for incoming connections
  • UDP sockets do not need listen(); send/receive directly with recvfrom() / sendto()
  • "mcast" automatically sets SO_BROADCAST (IPv4) or IPV6_ADD_MEMBERSHIP (IPv6)

net_connect([type], addr, port [, ttl [, secure]]) → socket | nil, err​

Creates a client socket and connects to a remote address.

Parameters:

ParameterTypeDefaultDescription
typestring"tcp"Socket type: "tcp", "udp", "mcast"
addrstringRequiredDestination address (IP or domain)
portnumberRequiredDestination port
ttlnumber1Multicast TTL ("mcast" only)
securebooleanfalseTCP+TLS client (for wss/https). May also be passed as the fourth argument, omitting ttl

Returns:

  • Success: socket object
  • Failure: nil, error string

Example:

-- TCP connection
local client, err = net_connect("192.168.1.100", 3000)
-- Equivalent to
local client, err = net_connect("tcp", "192.168.1.100", 3000)

-- UDP connection (no handshake; just set the default destination)
local client, err = net_connect("udp", "192.168.1.100", 9000)

-- Multicast connection (TTL=2, can cross one router)
local client, err = net_connect("mcast", "239.255.0.1", 5000, 2)

-- TLS connection (requires firmware TLS support; choose either form)
local tls, err = net_connect("api.example.com", 443, true)
local tls, err = net_connect("tcp", "api.example.com", 443, 1, true)

Notes:

  • TCP connection is nonblocking; connect() may return EINPROGRESS, which does not mean failure
  • IPv4/IPv6 are selected automatically from the address
  • Domain addresses trigger DNS resolution automatically
  • secure=true supports TCP only and also returns immediately. TCP connection and TLS handshake advance nonblockingly through subsequent send/recv/cando/net_select calls, so Copas retry loops drive the handshake unchanged. Certificate verification is mandatory (platform system certificates); SNI and hostname verification use the original addr. Connection/handshake errors surface through send/recv as nil,"tcp: ..."/"tls: ..."; sock:info("tls") reports "off"/"connect"/"handshake"/"on"/an error string. Firmware without TLS returns nil,"tls not compiled" for secure=true

net_select(read_table, write_table) → read_ready, write_ready [, err]​

Checks which sockets are ready for reading/writing. Zero timeout; returns immediately.

Parameters:

ParameterTypeDescription
read_tabletableArray of sockets to check for readability
write_tabletableArray of sockets to check for writability

Returns:

  • Success: two arrays of ready socket objects (only one ready array when only read_table is supplied)
  • No events: two empty tables
  • Error: two empty tables plus a third value—false for busy conditions (EAGAIN/EINPROGRESS), otherwise an error string

Example:

local readable, writable = net_select({sock1, sock2}, {sock3})
for _, s in ipairs(readable) do
-- s has readable data
end

Note: Usually used internally by Copas, not called directly. Call from _draw() if implementing your own event loop.


net_resolve(name) → table | nil, err​

Resolves a DNS name into an IP address list.

Parameters:

ParameterTypeDescription
namestringDomain or IP address

Returns:

  • Success: array of {family="inet"|"inet6", addr="x.x.x.x"}
  • Failure: nil, error information

Example:

local addrs, err = net_resolve("example.com")
if addrs then
for _, a in ipairs(addrs) do
printh(a.family .. " " .. a.addr)
end
end
-- Output: inet 93.184.216.34

Note: IP address strings bypass DNS queries and are parsed directly.


net_getinf() → table | nil, err​

Gets the local network interface list.

Returns:

  • Success: array of {name=, family=, addr=, mask=} (mask exists only when the netmask is parseable; interfaces without addresses are skipped)
  • Failure: nil, error information (not yet implemented on ESP32/Android/Windows; returns "ENS")

Example:

local ifaces = net_getinf()
if ifaces then
for _, iface in ipairs(ifaces) do
printh(iface.name .. " " .. iface.family .. " " .. iface.addr)
end
end

Note: Unavailable on ESP32-S3 targets; returns an error.


3. Socket Methods​

Socket objects returned by net_bind and net_connect support these methods.

sock:info([which]) → table​

Gets socket information.

Parameters:

ParameterTypeDescription
whichstringnil: basic information; "peer": peer; "socket": local endpoint; "tls": TLS state ("off"/"connect"/"handshake"/"on" or error string; always "off" for sockets created without secure). Unknown values return nil. Unrecognized family/type are "unknown"

Returns:

For which=nil, returns:

{
fd = 5, -- File descriptor
family = "inet", -- "inet" or "inet6"
type = "tcp", -- "tcp" or "udp"
listening = true, -- Whether this is a listening socket
multicast = false -- Whether multicast is enabled
}

For which="peer" or "socket", returns:

{
addr = "192.168.1.100", -- IP address
port = 8080, -- Port number
family = "inet" -- "inet" or "inet6"
}

Example:

-- Basic information
for k, v in pairs(sock:info()) do
printh(k .. ": " .. tostring(v))
end

-- Peer address
local peer = sock:info("peer")
printh("Connected to: " .. peer.addr .. ":" .. peer.port)

-- Local address
local me = sock:info("socket")
printh("Local: " .. me.addr .. ":" .. me.port)

sock:cando(send) → boolean​

Checks readability/writability (nonblocking probe).

Parameters:

ParameterTypeDescription
sendbooleanfalse/nil: check readability; true: check writability

Example:

if sock:cando(false) then
local data = sock:recv()
end

sock:accept() → client_socket, addr, port | false | nil, err​

Accepts a TCP connection (listening sockets only). Nonblocking; returns false if none is available.

Returns:

  • Connection available: new socket object + client IP + client port
  • No connection: false
  • Error: nil, error information

Example:

local server = net_bind("tcp", 8080)
-- Inside the _draw() loop
local client, addr, port = server:accept()
if client then
printh("New connection from " .. addr .. ":" .. port)
end

sock:recv([pattern [, prefix]]) → data [, err [, partial]]​

Receives TCP data. Nonblocking.

Parameters:

ParameterTypeDefaultDescription
patternstring/number"*l""*l": one line; "*a": all data; number: specified byte count
prefixstring""Existing data prepended to the result

Three return cases:

CaseReturns
Successdata, nil, nil
Timeout (no data)false, "timeout", partial_data
Closed/errornil, "closed"/errmsg, partial_data

Example:

-- Read a line
local line, err, partial = sock:recv("*l")

-- Read 1024 bytes
local data, err, partial = sock:recv(1024)

-- Read all data
local all, err = sock:recv("*a")

-- Continue reading with previously received partial data
local data, err, partial = sock:recv(1024, previous_partial)

sock:recvfrom([size]) → data, addr, port | false | nil, err​

Receives a UDP datagram (UDP sockets only). Nonblocking.

Parameters:

ParameterTypeDefaultDescription
sizenumber4096Maximum bytes to read (64KB limit; exceeding it raises Lua error "EBA")

Return values:

CaseReturns
Successdata, sender_ip, sender_port
No datafalse
Errornil, err

Example:

local server = net_bind("udp", "0.0.0.0", 9000)
-- Inside the _draw() loop
local data, addr, port = server:recvfrom()
if data then
printh("From " .. addr .. ":" .. port .. " got: " .. data)
end

sock:send(data [, from [, to]]) → last_index, nil, nil | false, nil, index | nil, err, index​

Sends TCP data. Nonblocking.

Parameters:

ParameterTypeDefaultDescription
datastringRequiredData to send
fromnumber1Starting position (1-based)
tonumber#dataEnding position

Return values:

CaseReturns
Successnext_position, nil, nil (next_position is the starting position for the next send)
Timeoutfalse, nil, last_sent_index
Errornil, err, last_sent_index

Example:

-- Simple send
local sent, err = sock:send("hello\n")

-- Resume sending the remaining unsent data
local idx = 1
while idx <= #data do
local next_idx, err, last = sock:send(data, idx)
if next_idx then
idx = next_idx + 1
elseif next_idx == false then
idx = last + 1 -- Timeout; retry next time
else
break -- Error
end
end

sock:sendto(data, addr, port) → size | false | nil, err​

Sends a UDP datagram to an address. Nonblocking.

Parameters:

ParameterTypeDescription
datastringData to send
addrstringDestination IP address
portnumberDestination port

Return values:

CaseReturns
Successsent_bytes (bytes sent)
Timeoutfalse
Errornil, err

Example:

local server = net_bind("udp", "0.0.0.0", 9000)
server:sendto("hello", "192.168.1.100", 8080)

sock:timeout([value]) → number​

Sets or gets the socket timeout.

Parameters:

ParameterTypeDescription
valuenumberTimeout in seconds (set if supplied, read only if omitted)

Returns: Current timeout in seconds. No return value (nil) until a timeout is set; returns a value only after a nonnegative timeout has been configured.

Note: Copas uses this timeout; it does not directly affect the underlying socket, which remains nonblocking.


sock:close() → true | nil, err​

Closes the socket and releases resources. GC also closes it automatically.

sock:close()

4. Copas Asynchronous Scheduler​

Copas is a cooperative coroutine scheduler that wraps nonblocking I/O so networking code can use a synchronous style.

Loading​

Copas is defined in colox_net.lua; load with #include:

usemod('net')
#include colox_net.lua

After loading, global copas and helpers net_protect, net_newtry are available.

net_protect(func) → function​

Wraps a function safely: table-valued errors thrown by net_newtry/HTTP are converted to (nil, err) returns; ordinary string errors propagate.

local safe_func = net_protect(function(a, b)
-- newtry-style errors return nil, errmsg instead of throwing
return do_something(a, b)
end)
local result, err = safe_func(1, 2)

net_newtry(finalizer) → function​

Creates a try wrapper that calls finalizer automatically on failure to clean up resources.

local try = net_newtry(function() sock:close() end)
-- If send fails, close the socket and raise an error automatically
try(sock:send("hello"))

Core Concepts​

Copas uses coroutines for asynchronous I/O:

  1. Call copas.receive() / copas.send() in a coroutine
  2. If the operation would block (no data/full buffer), the coroutine yields automatically
  3. Call copas.step() in _draw(); the scheduler checks all sockets
  4. Coroutines waiting on ready sockets resume

Essential: Call copas.step() every frame, or no network operation progresses.


copas.step() → boolean​

Runs one scheduling step. Call in each _draw() frame. false means nothing needed doing in this step.

Example:

function _draw()
copas.step()
end

copas.addthread(func [, ...]) → thread​

Creates a coroutine and starts it immediately.

Parameters:

ParameterTypeDescription
funcfunctionCoroutine function
...anyAdditional arguments passed to func

Returns: Coroutine object (usable with copas.removethread())

Example:

copas.addthread(function()
local client = net_connect("192.168.1.100", 3000)
if not client then return end

while true do
local data, err = copas.receive(client)
if data then
printh("Received: " .. data)
elseif err == "closed" then
printh("Connection closed")
break
end
end
end)

copas.removethread(thread)​

Removes a coroutine, stops it, and closes associated sockets.

local thread = copas.addthread(function() ... end)
-- Later
copas.removethread(thread)

copas.addserver(server, handler)​

Registers a server socket and connection handler.

Parameters:

ParameterTypeDescription
serversocketServer socket created by net_bind()
handlerfunctionNew-connection handler (receives the client socket)

Example:

local server = net_bind("tcp", 8080)
copas.addserver(server, function(client)
while true do
local data, err = copas.receive(client)
if not data then break end
copas.send(client, "Echo: " .. data .. "\n")
end
client:close()
end)

Notes:

  • TCP server: automatically creates a handler coroutine for each connection
  • UDP server: runs handler directly in a coroutine with copas.receivefrom() / copas.sendto() (a socket created with net_connect("udp",...) already has a default destination, so copas.send works directly)

copas.removeserver(server [, keep_open])​

Removes a registered server.

Parameters:

ParameterTypeDescription
serversocketServer socket
keep_openbooleantrue keeps it open; false (default) closes it

copas.receive(client [, pattern [, part [, timeout]]]) → data, err, partial​

Receives TCP data asynchronously. The coroutine yields automatically when no data is available.

Parameters:

ParameterTypeDefaultDescription
clientsocketRequiredTCP socket
patternstring/number"*l"Same pattern as sock:recv()
partstring""Existing partial data
timeoutnumberSocket timeoutReceive timeout in seconds

Example:

copas.addthread(function()
local client = net_connect("example.com", 80)
copas.send(client, "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n")
local response, err = copas.receive(client, "*a")
printh(response)
end)

copas.receivePartial(client [, pattern [, part [, timeout]]]) → data, err, partial​

Similar to copas.receive(), but for a numeric pattern returns once partial data arrives, without filling the requested byte count. *l/*a behave identically to receive.

Use for: Streaming when message boundaries do not matter.

local data, err, partial = copas.receivePartial(client, 1024, nil, 5)

copas.receivefrom(client [, size [, timeout]]) → data, addr, port​

Receives UDP datagrams asynchronously.

Parameters:

ParameterTypeDefaultDescription
clientsocketRequiredUDP socket
sizenumber8192Maximum bytes to read
timeoutnumberSocket timeoutTimeout in seconds

copas.send(client, data [, from [, to [, timeout]]]) → result, err, last_index​

Sends TCP data asynchronously. The coroutine yields automatically while the buffer is full.


copas.sendto(client, data, ip, port [, timeout]) → result, err​

Sends UDP datagrams asynchronously.


copas.sleep(sleeptime)​

Suspends the current coroutine for the specified seconds.

Parameters:

ParameterTypeDescription
sleeptimenumberSeconds; < 0 sleeps indefinitely (requires wakeup)
copas.addthread(function()
while true do
do_periodic_task()
copas.sleep(10) -- Run every 10 seconds
end
end)

copas.wakeup(thread)​

Wakes a coroutine sleeping in copas.sleep().

local thread = copas.addthread(function()
copas.sleep(-1) -- Wait indefinitely
printh("Woken up!")
end)
-- Later
copas.wakeup(thread)

copas.finished() → boolean​

Checks whether all tasks are complete (no active read/write sockets or sleeping coroutines).


copas.setErrorHandler(handler)​

Sets an error handler for the current coroutine.

copas.setErrorHandler(function(msg, co, skt)
printh("Error in coroutine: " .. tostring(msg))
end)

5. HTTP Client (nethttp)​

Copas-based HTTP/1.1 client supporting GET/POST, redirects, chunked transfer encoding, and multipart responses.

Loading​

usemod('net')
#include colox_net.lua
#include colox_http.lua

Global nethttp becomes available after loading.


nethttp.request(request_or_url [, body [, timeout]]) → result, code, headers, status​

Sends an HTTP request.

Simple GET​

local body, code, headers, status = nethttp.request("http://example.com/api")

Parameters:

ParameterTypeDescription
request_or_urlstringURL string (supports user:pass@host, generating Authorization: Basic automatically)
bodystringPOST body (nil means GET)
timeoutnumberTimeout in seconds

Returns (string URL form):

Return valueTypeDescription
resultstringResponse body
codenumberHTTP status code (200, 404, etc.)
headerstableResponse headers {name=value, ...} (lowercase keys, e.g. headers["content-length"])
statusstringStatus line (e.g. "HTTP/1.1 200 OK")

Table-form requests return numeric 1 first; collect the response body through sink.

POST Request (Simple URL String)​

local body = '{"key":"value"}'
local result, code = nethttp.request("http://example.com/api", body)

Advanced Request (Table Form)​

local json_body = '{"key":"value"}'
local t = {} -- Collect response body chunks
local req = {
url = "http://example.com/api",
method = "POST",
headers = {
["Content-Type"] = "application/json",
["Content-Length"] = #json_body,
},
source = nethttp.ltn12.source.string(json_body),
sink = nethttp.ltn12.sink.table(t),
}
local result, code, headers, status = nethttp.request(req)
local response_body = table.concat(t)

Request table fields:

FieldTypeDescription
urlstringRequest URL
methodstringHTTP method ("GET", "POST", etc.)
headerstableRequest headers {name=value}
sourcefunctionLTN12 source for the request body
sinkfunctionLTN12 sink for the response body
stepfunctionLTN12 pump step function
proxystringHTTP proxy address
redirectbooleanFollow redirects (default true; only 301/302/303/307 for GET/HEAD, at most 5 times)
connecttimeoutnumberConnection timeout (seconds)
_on_headerfunctionCallback after receiving response headers; false aborts
_noclosebooleantrue preserves the connection (keep-alive)
_multiparttableMultipart response handler

nethttp.open(host, port) → http_connection​

Creates an HTTP connection (low-level API). Usually called internally by request(), not directly. Returns nil on connection failure, without an error string.


Common Patterns​

JSON POST Request​

copas.addthread(function()
local json = '{"name":"test"}'
local t = {}
local result, code, headers = nethttp.request({
url = "http://api.example.com/data",
method = "POST",
headers = {
["Content-Type"] = "application/json",
Accept = "application/json",
["Content-Length"] = #json,
},
source = nethttp.ltn12.source.string(json),
sink = nethttp.ltn12.sink.table(t),
})
if code == 200 then
printh("Response: " .. table.concat(t))
end
end)

Simple GET Request​

copas.addthread(function()
local body, code = nethttp.request("http://example.com/data")
if body then
printh("Got: " .. body)
end
end)

Stock Data Example​

copas.addthread(function()
local r, code = nethttp.request("http://qt.gtimg.cn/q=s_sh000001")
if type(r) == 'string' then
printh(r)
end
end)

6. WebSocket Client (ws)​

Copas-based WebSocket client (RFC 6455), supporting ws:// and wss:// in the client role. Supports text/binary messages, fragment reassembly, control frames (ping/pong/close), automatic pong replies, and closing handshakes. All outgoing client frames are masked, per RFC 6455 §5.1.

wss:// requires firmware TLS sockets (the secure parameter of net_connect; see section 2). Without TLS, ws_connect fails fast for wss:// with tls not compiled. No permessage-deflate, server role, or automatic reconnection. opts.timeout in seconds is the total connection/handshake/upgrade budget (default 15s), especially important for wss.

Loading​

usemod('net')
#include colox_net.lua
#include colox_ws.lua -- Required (colox_http.lua is optional; include it only when also using the other examples in this topic)

After loading, call ws_connect directly. The host globals b64encode/sha1sum provide handshake base64/SHA-1 (C implementation; see lua.md); colox_http.lua is not mandatory.

As with other Copas code, blocking ws:* calls must run in coroutines created by copas.addthread, driven by copas.step() in the cartridge's _draw(). colox_ws.lua starts no additional loop/timer/thread itself.


ws_connect(url [, opts]) → ws | nil, err​

Connects to a WebSocket server and completes the RFC 6455 handshake.

Parameters:

ParameterTypeDefaultDescription
urlstringRequiredws://host[:port]/path (default port 80) / wss:// (default port 443)
opts.headerstablenilAdditional request headers {name=value, ...}
opts.verify_acceptbooleantrueVerify Sec-WebSocket-Accept; enabled by default, explicitly disable with false
opts.timeoutnumber15Total handshake budget in seconds, shared by sending and response reading

Returns: ws on success, nil, err on failure (err may be "connect failed", "bad upgrade response", "bad Sec-WebSocket-Accept", etc.).

Notes:

  • Response headers Upgrade: websocket and Connection: Upgrade are always verified (RFC 6455 §4.2.2); mismatch fails immediately.
  • Sec-WebSocket-Accept is verified by pure Lua SHA-1 by default; disable with opts.verify_accept = false if needed.

ws:receive() → msg | nil, err​

Receives the next WebSocket message, blocking within a coroutine (must be called in one).

Returns:

CaseReturns
Message receivedmsg, nil, where msg = { op = "text"\|"binary"\|"close", data = string } (incoming ping gets automatic pong; pong is silently discarded; neither is exposed as a message)
Closed/errornil, err, with err ∈ { "closed", "timeout", <protocol error> }

Notes:

  • For op == "close", msg.data is the numeric status code from the peer (or nil).
  • Automatically responds to ping with a matching-payload pong, without exposing it as a message.
  • Fragments are reassembled automatically; interleaved control frames are handled correctly (RFC 6455 §5.4).
  • Protocol errors (nonzero RSV bits, unknown opcodes, masked server frames, etc.) send close code 1002 and return nil, "closed".

ws:send(data [, kind]) → ok | nil, err​

Sends a message.

ParameterTypeDefaultDescription
datastringRequiredMessage content (nonstrings use tostring)
kindstring"text""text" or "binary"

Returns: true | nil, err. Send timeout also returns nil, "timeout" (connection considered closed).


ws:send_control(kind [, payload]) → ok | nil, err​

Sends a control frame.

ParameterTypeDescription
kindstring"ping" or "pong"
payloadstringPayload, at most 125 bytes
ws:send_control("ping", "hi")

ws:close([code [, reason]]) → ok | nil, err​

Sends a close frame and closes the connection (default status 1000). Idempotent; repeated calls are safe.

ws:close(1000, "bye")

ws:isclosed() → boolean​

Returns whether the connection is closed (close frame received/sent, or read/write error).


Complete Example​

coloX-16
version 1
__lua__

usemod('net')
#include colox_net.lua
#include colox_http.lua
#include colox_ws.lua

copas.addthread(function()
local ws, err = ws_connect("ws://echo.websocket.events")
if not ws then
printh("ws connect failed: " .. tostring(err))
return
end

ws:send("hello coloX ws")
while not ws:isclosed() do
local msg, rerr = ws:receive()
if msg then
printh("recv " .. msg.op .. ": " .. tostring(msg.data))
if msg.op == "close" then break end
else
printh("recv err: " .. tostring(rerr))
break
end
end
end)

function _draw()
copas.step()
end

7. URL Parsing (nethttp)​

colox_http.lua includes URL parsing/building functions on the nethttp table (no independent global url).

nethttp.parse(url_string [, default]) → table​

Parses a URL into a component table.

local parsed = nethttp.parse("http://user:pass@example.com:8080/path?q=1#frag")
-- Result:
-- {
-- scheme = "http",
-- authority = "user:pass@example.com:8080",
-- userinfo = "user:pass",
-- user = "user",
-- password = "pass",
-- host = "example.com",
-- port = "8080",
-- path = "/path",
-- query = "q=1",
-- fragment = "frag",
-- }

nethttp.build(parsed) → string​

Builds a URL from components.

local u = nethttp.build({
scheme = "http",
host = "example.com",
path = "/api",
query = "key=value"
})
-- → "http://example.com/api?key=value"

nethttp.absolute(base_url, relative_url) → string​

Resolves a relative URL into an absolute URL.

local abs = nethttp.absolute("http://example.com/dir/page", "../other")
-- → "http://example.com/other"

nethttp.escape(s) → string​

URL encoding.

nethttp.escape("hello world!")
-- → "hello%20world%21"

nethttp.unescape(s) → string​

URL decoding.

nethttp.unescape("hello%20world%21")
-- → "hello world!"

nethttp.parse_path(path) → table​

Parses a URL path into segments.

local segments = nethttp.parse_path("/a/b/c")
-- → {"a", "b", "c", is_absolute=1}

nethttp.build_path(parsed [, unsafe]) → string​

Builds a path from segments.

nethttp.build_path({"a", "b", "c", is_absolute=1})
-- → "/a/b/c"

8. LTN12 Streams​

LTN12 (Lua Technical Note 12) is LuaSocket's stream model, fully implemented by coloX in colox_http.lua. Access it through nethttp.ltn12.

Concepts​

ConceptDescription
SourceData producer, returning a chunk per call and nil at the end
SinkData consumer, accepting a chunk and returning success status
FilterData transformer, taking a chunk and returning transformed data
PumpDrives data from Source to Sink

Source​

nethttp.ltn12.source.string(s) → source​

Creates a string source.

local src = nethttp.ltn12.source.string('{"key":"value"}')

nethttp.ltn12.source.empty() → source​

Creates an empty source.

nethttp.ltn12.source.cat(...) → source​

Concatenates multiple sources.

nethttp.ltn12.source.chain(src, filter [, ...]) → source​

Chains a source through one or more filters.

nethttp.ltn12.source.file(handle) → source​

Creates a file source (if the platform supports file I/O).

Sink​

nethttp.ltn12.sink.table([t]) → sink, t​

Creates a table collector, collecting every chunk into a table.

local t = {}
local sink = nethttp.ltn12.sink.table(t)
-- ... pump data into the sink
local full_data = table.concat(t)

nethttp.ltn12.sink.null() → sink​

Creates a sink discarding all data.

nethttp.ltn12.sink.file(handle) → sink​

Creates a file-writing sink.

nethttp.ltn12.sink.chain(filter, sink [, ...]) → sink​

Passes data through a filter into a sink.

Filter​

nethttp.ltn12.filter.cycle(low, ctx, extra) → filter​

Creates a cycling filter.

nethttp.ltn12.filter.chain(...) → filter​

Chains filters.

Pump​

nethttp.ltn12.pump.all(source, sink [, step]) → result, err​

Pumps all data from source to sink.

local src = nethttp.ltn12.source.string("hello world")
local snk = nethttp.ltn12.sink.null()
nethttp.ltn12.pump.all(src, snk)

nethttp.ltn12.pump.step(source, sink) → result, err​

Pumps one chunk.


9. Complete Examples​

Example 1: TCP Echo Server​

coloX-16
version 1
__lua__

usemod('net')
#include colox_net.lua

local server = net_bind("tcp", 8080)
if not server then
printh("Failed to bind")
return
end
printh("TCP server listening on port 8080")

copas.addserver(server, function(client)
local peer = client:info("peer")
printh("Client connected: " .. peer.addr .. ":" .. peer.port)

while true do
local data, err = copas.receive(client)
if not data then
printh("Client disconnected: " .. (err or "unknown"))
break
end
copas.send(client, "Echo: " .. data .. "\n")
end
client:close()
end)

function _draw()
copas.step()
end

Example 2: Sending and Receiving UDP Datagrams​

coloX-16
version 1
__lua__

usemod('net')

local server = net_bind("udp", "0.0.0.0", 8898)
if not server then
printh("Bind failed")
return
end
printh("UDP server on port 8898")

function _draw()
local data, addr, port = server:recvfrom()
if data then
data = string.gsub(data, "\n$", "")
print("From " .. addr .. ":" .. port .. " '" .. data .. "'", 0, 0)
server:sendto("Reply: " .. data .. "\n", addr, port)
end
end

Example 3: HTTP GET Request​

coloX-16
version 1
__lua__

usemod('net')
#include colox_net.lua
#include colox_http.lua

copas.addthread(function()
local body, code, headers = nethttp.request("http://httpbin.org/get")
if body then
printh("Status: " .. tostring(code))
printh("Body: " .. body)
else
printh("Request failed: " .. tostring(code))
end
end)

function _draw()
copas.step()
end

Example 4: HTTP POST JSON Data​

coloX-16
version 1
__lua__

usemod('net')
#include colox_net.lua
#include colox_http.lua

copas.addthread(function()
local json_body = '{"device":"coloX","value":42}'
local t = {}

local result, code, headers = nethttp.request({
url = "http://httpbin.org/post",
method = "POST",
headers = {
["Content-Type"] = "application/json",
["Content-Length"] = #json_body,
},
source = nethttp.ltn12.source.string(json_body),
sink = nethttp.ltn12.sink.table(t),
})

if code == 200 then
printh("Response: " .. table.concat(t))
end
end)

function _draw()
copas.step()
end

Example 5: TCP Client Connection​

coloX-16
version 1
__lua__

usemod('net')
#include colox_net.lua

local client, err = net_connect("192.168.1.100", 3000)
if not client then
printh("Connect failed: " .. err)
return
end

client:timeout(5) -- 5-second send/receive timeout (without it, the timeout branch below effectively never runs)

copas.addthread(function()
-- Send data (nonblocking connection; the handshake completes on the first send)
copas.send(client, "Hello from coloX\n")

-- Inspect the peer after connecting
local peer = client:info("peer")
if peer then
printh("Connected to " .. peer.addr .. ":" .. peer.port)
end

-- Receive continuously
while true do
local data, err = copas.receive(client)
if data then
printh("Got: " .. data)
elseif err == "closed" then
printh("Server closed connection")
break
elseif err == "timeout" then
copas.send(client, "\n") -- Heartbeat
end
end
client:close()
end)

function _draw()
copas.step()
end

Example 6: DNS Resolution and Network Interface Queries​

coloX-16
version 1
__lua__

usemod('net')

-- DNS resolution
local addrs = net_resolve("example.com")
if addrs then
for _, a in ipairs(addrs) do
printh(a.family .. " → " .. a.addr)
end
end

-- Local network interfaces
local ifaces = net_getinf()
if ifaces then
for _, ifa in ipairs(ifaces) do
printh(ifa.name .. " " .. ifa.family .. " " .. ifa.addr)
end
end

10. Complete API Index​

Global Functions​

FunctionReturnsDescription
net_bind([type], [addr], port [, backlog])socket | nil, errCreate a server socket
net_connect([type], addr, port [, ttl [, secure]])socket | nil, errConnect to a remote server (secure=true for TLS)
net_select(read_tbl, write_tbl)ready_r, ready_w [, err]Check socket readiness
net_resolve(name)table | nil, errDNS resolution
net_getinf()table | nil, errGet network interface list

Socket Methods​

MethodReturnsDescription
sock:info([which])tableSocket information
sock:cando(send)booleanCheck readability/writability
sock:accept()socket, addr, port | falseAccept a TCP connection
sock:recv([pattern [, prefix]])data [, err, partial]Receive TCP data
sock:recvfrom([size])data, addr, port | falseReceive UDP datagrams
sock:send(data [, from, to])idx, nil, nil | false/nil, ...Send TCP data
sock:sendto(data, addr, port)size | false | nil, errSend UDP datagrams
sock:timeout([value])numberSet/get timeout
sock:close()true | nil, errClose socket

Copas Methods (Require #include colox_net.lua)​

MethodDescription
net_protect(func)Safe wrapper (convert exceptions to (nil, err))
net_newtry(finalizer)Create try wrapper (automatic cleanup on failure)
copas.step()Run one scheduling step
copas.addthread(func [, ...])Create a coroutine
copas.removethread(thread)Remove a coroutine
copas.addserver(server, handler)Register a server
copas.removeserver(server [, keep_open])Remove a server
copas.receive(client [, pattern [, part [, timeout]]])Asynchronous TCP receive
copas.receivePartial(client [, pattern [, part [, timeout]]])Asynchronous partial receive
copas.receivefrom(client [, size [, timeout]])Asynchronous UDP receive
copas.send(client, data [, from [, to [, timeout]]])Asynchronous TCP send
copas.sendto(client, data, ip, port [, timeout])Asynchronous UDP send
copas.sleep(sleeptime)Suspend a coroutine
copas.wakeup(thread)Wake a coroutine
copas.finished()Check completion
copas.setErrorHandler(handler)Set error handling
copas.autocloseAutomatic close flag (default true)

HTTP Methods (Require #include colox_http.lua)​

MethodDescription
nethttp.request(req_or_url [, body [, timeout]])Send HTTP request
nethttp.open(host, port [, create [, timeout]])Create HTTP connection
nethttp.TIMEOUTDefault timeout (60 seconds)
nethttp.PORTDefault port (80)
nethttp.USERAGENTUser-Agent("coloX")

WebSocket Methods (Require #include colox_net.lua and colox_ws.lua; colox_http.lua Optional)​

MethodDescription
ws_connect(url [, opts])Connect to ws server and handshake; returns ws \| nil, err
ws:receive()Blocking receive of one message; returns msg \| nil, err
ws:send(data [, kind])Send text/binary message; kind ∈ "text" (default)/"binary"
ws:send_control(kind [, payload])Send ping/pong control frame; payload ≤125 bytes
ws:close([code [, reason]])Send close frame and close connection (default 1000), idempotent
ws:isclosed()Whether connection is closed

URL Methods​

MethodDescription
nethttp.parse(url [, default])Parse URL
nethttp.build(parsed)Build URL
nethttp.absolute(base, relative)Resolve absolute URL
nethttp.escape(s)URL encoding
nethttp.unescape(s)URL decoding
nethttp.parse_path(path)Parse path
nethttp.build_path(parsed [, unsafe])Build path

LTN12 Methods​

MethodDescription
nethttp.ltn12.source.string(s)String source
nethttp.ltn12.source.empty()Empty source
nethttp.ltn12.source.cat(...)Concatenate sources
nethttp.ltn12.source.chain(src, f, ...)Chained source
nethttp.ltn12.source.file(handle)File source
nethttp.ltn12.sink.table([t])Table collector
nethttp.ltn12.sink.null()Discarding sink
nethttp.ltn12.sink.file(handle)File sink
nethttp.ltn12.sink.chain(f, snk, ...)Chained sink
nethttp.ltn12.filter.cycle(low, ctx, extra)Cycling filter
nethttp.ltn12.filter.chain(...)Chained filter
nethttp.ltn12.pump.all(src, snk [, step])Pump all data
nethttp.ltn12.pump.step(src, snk)Pump one chunk

11. Platform Differences (Windows)​

Windows differs from other platforms as follows:

ItemWindows behaviorDescription
net_getinfReturns nil,"ENS"Not yet implemented (same on ESP32/Android)
TLS (secure=true)AvailableCertificate verification uses the Windows system certificate store (other desktops use system CA, with the same semantics)
Sockets per net_select setLimit 64; exceeding it raises Lua error "EFD"Other platforms cap at 1024 and silently truncate; Windows errors instead of dropping events
Nonblocking connect failureFailed connections also appear writable in net_select (except set merged into write results); send/recv return the concrete errorSame Copas semantics as POSIX checking errors after writability
Error messagesEquivalent text mapped from WSA codes (e.g. "connection refused"); unmapped codes use "wsa error <n>"Equivalent to other platforms; only unmapped codes have the wsa error prefix
Local firewallConnecting to an unlistened port may yield neither writability nor error (firewall drops RST, leaving it in flight)—system behavior, not a module defectTest rejection using a peer actively sending RST, not a bare port