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
- Architecture
- Global functions
- Socket methods
- Copas asynchronous scheduler
- HTTP client (nethttp)
- WebSocket client (ws)
- URL parsing (nethttp)
- LTN12 streams
- Complete examples
- 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.luaimplements 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_selectuses 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:
| Parameter | Type | Default | Description |
|---|---|---|---|
type | string | "tcp" | Socket type: "tcp", "udp", "mcast" |
addr | string | "0.0.0.0" | Bind address; nil binds all interfaces |
port | number | Required | Port number |
backlog | number | 2 | TCP 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; useaccept()for incoming connections - UDP sockets do not need
listen(); send/receive directly withrecvfrom()/sendto() "mcast"automatically setsSO_BROADCAST(IPv4) orIPV6_ADD_MEMBERSHIP(IPv6)
net_connect([type], addr, port [, ttl [, secure]]) → socket | nil, err
Creates a client socket and connects to a remote address.
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
type | string | "tcp" | Socket type: "tcp", "udp", "mcast" |
addr | string | Required | Destination address (IP or domain) |
port | number | Required | Destination port |
ttl | number | 1 | Multicast TTL ("mcast" only) |
secure | boolean | false | TCP+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 returnEINPROGRESS, which does not mean failure - IPv4/IPv6 are selected automatically from the address
- Domain addresses trigger DNS resolution automatically
secure=truesupports TCP only and also returns immediately. TCP connection and TLS handshake advance nonblockingly through subsequentsend/recv/cando/net_selectcalls, so Copas retry loops drive the handshake unchanged. Certificate verification is mandatory (platform system certificates); SNI and hostname verification use the originaladdr. Connection/handshake errors surface throughsend/recvasnil,"tcp: ..."/"tls: ...";sock:info("tls")reports"off"/"connect"/"handshake"/"on"/an error string. Firmware without TLS returnsnil,"tls not compiled"forsecure=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:
| Parameter | Type | Description |
|---|---|---|
read_table | table | Array of sockets to check for readability |
write_table | table | Array of sockets to check for writability |
Returns:
- Success: two arrays of ready socket objects (only one ready array when only
read_tableis supplied) - No events: two empty tables
- Error: two empty tables plus a third value—
falsefor 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:
| Parameter | Type | Description |
|---|---|---|
name | string | Domain 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=}(maskexists 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:
| Parameter | Type | Description |
|---|---|---|
which | string | nil: 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:
| Parameter | Type | Description |
|---|---|---|
send | boolean | false/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:
| Parameter | Type | Default | Description |
|---|---|---|---|
pattern | string/number | "*l" | "*l": one line; "*a": all data; number: specified byte count |
prefix | string | "" | Existing data prepended to the result |
Three return cases:
| Case | Returns |
|---|---|
| Success | data, nil, nil |
| Timeout (no data) | false, "timeout", partial_data |
| Closed/error | nil, "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:
| Parameter | Type | Default | Description |
|---|---|---|---|
size | number | 4096 | Maximum bytes to read (64KB limit; exceeding it raises Lua error "EBA") |
Return values:
| Case | Returns |
|---|---|
| Success | data, sender_ip, sender_port |
| No data | false |
| Error | nil, 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:
| Parameter | Type | Default | Description |
|---|---|---|---|
data | string | Required | Data to send |
from | number | 1 | Starting position (1-based) |
to | number | #data | Ending position |
Return values:
| Case | Returns |
|---|---|
| Success | next_position, nil, nil (next_position is the starting position for the next send) |
| Timeout | false, nil, last_sent_index |
| Error | nil, 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:
| Parameter | Type | Description |
|---|---|---|
data | string | Data to send |
addr | string | Destination IP address |
port | number | Destination port |
Return values:
| Case | Returns |
|---|---|
| Success | sent_bytes (bytes sent) |
| Timeout | false |
| Error | nil, 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:
| Parameter | Type | Description |
|---|---|---|
value | number | Timeout 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:
- Call
copas.receive()/copas.send()in a coroutine - If the operation would block (no data/full buffer), the coroutine yields automatically
- Call
copas.step()in_draw(); the scheduler checks all sockets - 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:
| Parameter | Type | Description |
|---|---|---|
func | function | Coroutine function |
... | any | Additional 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:
| Parameter | Type | Description |
|---|---|---|
server | socket | Server socket created by net_bind() |
handler | function | New-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 withnet_connect("udp",...)already has a default destination, socopas.sendworks directly)
copas.removeserver(server [, keep_open])
Removes a registered server.
Parameters:
| Parameter | Type | Description |
|---|---|---|
server | socket | Server socket |
keep_open | boolean | true 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:
| Parameter | Type | Default | Description |
|---|---|---|---|
client | socket | Required | TCP socket |
pattern | string/number | "*l" | Same pattern as sock:recv() |
part | string | "" | Existing partial data |
timeout | number | Socket timeout | Receive 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:
| Parameter | Type | Default | Description |
|---|---|---|---|
client | socket | Required | UDP socket |
size | number | 8192 | Maximum bytes to read |
timeout | number | Socket timeout | Timeout 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:
| Parameter | Type | Description |
|---|---|---|
sleeptime | number | Seconds; < 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:
| Parameter | Type | Description |
|---|---|---|
request_or_url | string | URL string (supports user:pass@host, generating Authorization: Basic automatically) |
body | string | POST body (nil means GET) |
timeout | number | Timeout in seconds |
Returns (string URL form):
| Return value | Type | Description |
|---|---|---|
result | string | Response body |
code | number | HTTP status code (200, 404, etc.) |
headers | table | Response headers {name=value, ...} (lowercase keys, e.g. headers["content-length"]) |
status | string | Status line (e.g. "HTTP/1.1 200 OK") |
Table-form requests return numeric
1first; collect the response body throughsink.
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:
| Field | Type | Description |
|---|---|---|
url | string | Request URL |
method | string | HTTP method ("GET", "POST", etc.) |
headers | table | Request headers {name=value} |
source | function | LTN12 source for the request body |
sink | function | LTN12 sink for the response body |
step | function | LTN12 pump step function |
proxy | string | HTTP proxy address |
redirect | boolean | Follow redirects (default true; only 301/302/303/307 for GET/HEAD, at most 5 times) |
connecttimeout | number | Connection timeout (seconds) |
_on_header | function | Callback after receiving response headers; false aborts |
_noclose | boolean | true preserves the connection (keep-alive) |
_multipart | table | Multipart 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 (thesecureparameter ofnet_connect; see section 2). Without TLS,ws_connectfails fast forwss://withtls not compiled. Nopermessage-deflate, server role, or automatic reconnection.opts.timeoutin 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 bycopas.addthread, driven bycopas.step()in the cartridge's_draw().colox_ws.luastarts 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:
| Parameter | Type | Default | Description |
|---|---|---|---|
url | string | Required | ws://host[:port]/path (default port 80) / wss:// (default port 443) |
opts.headers | table | nil | Additional request headers {name=value, ...} |
opts.verify_accept | boolean | true | Verify Sec-WebSocket-Accept; enabled by default, explicitly disable with false |
opts.timeout | number | 15 | Total 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: websocketandConnection: Upgradeare always verified (RFC 6455 §4.2.2); mismatch fails immediately. Sec-WebSocket-Acceptis verified by pure Lua SHA-1 by default; disable withopts.verify_accept = falseif needed.
ws:receive() → msg | nil, err
Receives the next WebSocket message, blocking within a coroutine (must be called in one).
Returns:
| Case | Returns |
|---|---|
| Message received | msg, 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/error | nil, err, with err ∈ { "closed", "timeout", <protocol error> } |
Notes:
- For
op == "close",msg.datais the numeric status code from the peer (ornil). - Automatically responds to
pingwith a matching-payloadpong, 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
data | string | Required | Message content (nonstrings use tostring) |
kind | string | "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.
| Parameter | Type | Description |
|---|---|---|
kind | string | "ping" or "pong" |
payload | string | Payload, 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
| Concept | Description |
|---|---|
| Source | Data producer, returning a chunk per call and nil at the end |
| Sink | Data consumer, accepting a chunk and returning success status |
| Filter | Data transformer, taking a chunk and returning transformed data |
| Pump | Drives 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
| Function | Returns | Description |
|---|---|---|
net_bind([type], [addr], port [, backlog]) | socket | nil, err | Create a server socket |
net_connect([type], addr, port [, ttl [, secure]]) | socket | nil, err | Connect 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, err | DNS resolution |
net_getinf() | table | nil, err | Get network interface list |
Socket Methods
| Method | Returns | Description |
|---|---|---|
sock:info([which]) | table | Socket information |
sock:cando(send) | boolean | Check readability/writability |
sock:accept() | socket, addr, port | false | Accept a TCP connection |
sock:recv([pattern [, prefix]]) | data [, err, partial] | Receive TCP data |
sock:recvfrom([size]) | data, addr, port | false | Receive UDP datagrams |
sock:send(data [, from, to]) | idx, nil, nil | false/nil, ... | Send TCP data |
sock:sendto(data, addr, port) | size | false | nil, err | Send UDP datagrams |
sock:timeout([value]) | number | Set/get timeout |
sock:close() | true | nil, err | Close socket |
Copas Methods (Require #include colox_net.lua)
| Method | Description |
|---|---|
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.autoclose | Automatic close flag (default true) |
HTTP Methods (Require #include colox_http.lua)
| Method | Description |
|---|---|
nethttp.request(req_or_url [, body [, timeout]]) | Send HTTP request |
nethttp.open(host, port [, create [, timeout]]) | Create HTTP connection |
nethttp.TIMEOUT | Default timeout (60 seconds) |
nethttp.PORT | Default port (80) |
nethttp.USERAGENT | User-Agent("coloX") |
WebSocket Methods (Require #include colox_net.lua and colox_ws.lua; colox_http.lua Optional)
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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:
| Item | Windows behavior | Description |
|---|---|---|
net_getinf | Returns nil,"ENS" | Not yet implemented (same on ESP32/Android) |
TLS (secure=true) | Available | Certificate verification uses the Windows system certificate store (other desktops use system CA, with the same semantics) |
Sockets per net_select set | Limit 64; exceeding it raises Lua error "EFD" | Other platforms cap at 1024 and silently truncate; Windows errors instead of dropping events |
| Nonblocking connect failure | Failed connections also appear writable in net_select (except set merged into write results); send/recv return the concrete error | Same Copas semantics as POSIX checking errors after writability |
| Error messages | Equivalent 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 firewall | Connecting to an unlistened port may yield neither writability nor error (firewall drops RST, leaving it in flight)—system behavior, not a module defect | Test rejection using a peer actively sending RST, not a bare port |