coloX Net 网络模块 Lua 编程指南
coloX 网络模块提供 TCP/UDP/Multicast 套接字、异步 I/O 调度器 (Copas)、HTTP 客户端、URL 解析及 LTN12 数据流处理能力,适用于嵌入式网络通信和 HTTP API 调用场景。
启用方式
使用 usemod('net') 开启 net 模块,返回 true 表示成功。
usemod('net')
启用后,以下全局函数和套接字对象即可使用。Copas 调度器和 HTTP 客户端需要额外 #include Lua 脚本(见后文)。
目录
- 架构概览
- 全局函数
- Socket 对象方法
- Copas 异步调度器
- HTTP 客户端 (nethttp)
- WebSocket 客户端 (ws)
- URL 解析 (nethttp)
- LTN12 数据流
- 综合示例
- 完整 API 索引
1. 架构概览
coloX 网络模块分为三层:
┌─────────────────────────────────────────────┐
│ 应用层: nethttp.request() │ HTTP 请求
├─────────────────────────────────────────────┤
│ 调度层: copas.step() / copas.addthread() │ 协程异步 I/O
├─────────────────────────────────────────────┤
│ 传输层: net_bind / net_connect / socket │ TCP/UDP/Multicast
└─────────────────────────────────────────────┘
- 传输层 — 宿主内置的原生传输实现,提供非阻塞套接字操作
- 调度层 — 纯 Lua 实现(colox_net.lua),基于协程的协作式多任务
- 应用层 — 纯 Lua 实现(colox_http.lua),HTTP/1.1 客户端;
colox_ws.lua在 Copas 之上实现 WebSocket 客户端
重要特性
- 所有套接字默认非阻塞 — 套接字读写不会阻塞帧循环;但 DNS 域名解析是同步阻塞的(冷缓存时可能卡顿若干毫秒),直连 IP 无此问题
- 无
select超时 —net_select的 timeout 固定为 0,立即返回 - 协程驱动 — Copas 调度器在每帧
_draw()中调用copas.step()驱动所有网络 I/O - 超时检测与断线清理 — Copas 内置超时检测和断线清理(无自动重连,重连需自己实现)
2. 全局函数
net_bind([type], [addr], port [, backlog]) → socket | nil, err
创建服务端套接字,绑定到指定端口并开始监听。
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
type | string | "tcp" | 套接字类型:"tcp"、"udp"、"mcast" |
addr | string | "0.0.0.0" | 绑定地址,nil 则绑定所有接口 |
port | number | 必填 | 端口号 |
backlog | number | 2 | TCP 监听队列长度 |
返回:
- 成功:socket 对象
- 失败:
nil, 错误信息字符串
示例:
-- TCP 服务端 (监听所有接口的 8080 端口)
local server, err = net_bind("tcp", 8080)
-- 等价于
local server, err = net_bind("tcp", nil, 8080, 2)
-- UDP 服务端 (绑定到指定地址)
local server, err = net_bind("udp", "192.168.1.100", 9000)
-- 多播 (Multicast)
local server, err = net_bind("mcast", "239.255.0.1", 5000)
说明:
- TCP 套接字会自动调用
listen(),之后可通过accept()接受连接 - UDP 套接字不需要
listen(),直接通过recvfrom()/sendto()收发 "mcast"类型会自动设置SO_BROADCAST(IPv4)或IPV6_ADD_MEMBERSHIP(IPv6)
net_connect([type], addr, port [, ttl [, secure]]) → socket | nil, err
创建客户端套接字并连接到远程地址。
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
type | string | "tcp" | 套接字类型:"tcp"、"udp"、"mcast" |
addr | string | 必填 | 目标地址(IP 或域名) |
port | number | 必填 | 目标端口 |
ttl | number | 1 | 多播 TTL(仅 "mcast" 类型有效) |
secure | boolean | false | TCP+TLS 客户端(wss/https 用)。也可省略 ttl 直接传第 4 参 |
返回:
- 成功:socket 对象
- 失败:
nil, 错误信息字符串
示例:
-- TCP 连接
local client, err = net_connect("192.168.1.100", 3000)
-- 等价于
local client, err = net_connect("tcp", "192.168.1.100", 3000)
-- UDP 连接 (不需要真正握手,仅设置默认目标)
local client, err = net_connect("udp", "192.168.1.100", 9000)
-- 多播连接 (TTL=2,可跨一个路由器)
local client, err = net_connect("mcast", "239.255.0.1", 5000, 2)
-- TLS 连接(需固件支持 TLS;写法二选一)
local tls, err = net_connect("api.example.com", 443, true)
local tls, err = net_connect("tcp", "api.example.com", 443, 1, true)
说明:
- TCP 连接是非阻塞的,
connect()可能返回EINPROGRESS,这不代表失败 - 支持 IPv4 和 IPv6,根据地址自动判断
- 域名地址会自动进行 DNS 解析
secure=true仅支持 TCP:发起后同样是立即返回,TCP 连接与 TLS 握手在后台非阻塞推进,由后续send/recv/cando/net_select每次调用逐步完成——因此 Copas 的收发重试环无需任何改动即可驱动握手。证书校验强制开启(使用平台系统证书),SNI 与域名校验使用addr原文。握手/连接错误经send/recv以nil,"tcp: ..."/"tls: ..."冒出;sock:info("tls")可查询"off"/"connect"/"handshake"/"on"/错误串。固件未编入 TLS 时传secure=true返回nil,"tls not compiled"
net_select(read_table, write_table) → read_ready, write_ready [, err]
检查套接字集合中哪些已就绪(可读/可写)。零超时,立即返回。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
read_table | table | 要检查可读性的 socket 对象数组 |
write_table | table | 要检查可写性的 socket 对象数组 |
返回:
- 成功:两个数组,包含已就绪的 socket 对象(只传
read_table时只返回一个就绪表) - 无事件:两个空表
- 出错:两个空表 + 第三返回值——繁忙类(EAGAIN/EINPROGRESS)为
false,其余为错误信息串
示例:
local readable, writable = net_select({sock1, sock2}, {sock3})
for _, s in ipairs(readable) do
-- s 有数据可读
end
说明: 通常不需要直接调用此函数,Copas 调度器内部使用。如果自己实现事件循环,可在 _draw() 中调用。
net_resolve(name) → table | nil, err
DNS 域名解析,返回 IP 地址列表。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
name | string | 域名或 IP 地址 |
返回:
- 成功:数组表,每个元素
{family="inet"|"inet6", addr="x.x.x.x"} - 失败:
nil, 错误信息
示例:
local addrs, err = net_resolve("example.com")
if addrs then
for _, a in ipairs(addrs) do
printh(a.family .. " " .. a.addr)
end
end
-- 输出: inet 93.184.216.34
说明: IP 地址字符串会跳过 DNS 查询,直接解析。
net_getinf() → table | nil, err
获取本机网络接口列表。
返回:
- 成功:数组表,每个元素
{name=, family=, addr=, mask=}(mask仅在 netmask 可解析时存在;无地址的接口整条被跳过) - 失败:
nil, 错误信息(ESP32/Android/Windows 上暂未实现,返回"ENS"错误)
示例:
local ifaces = net_getinf()
if ifaces then
for _, iface in ipairs(ifaces) do
printh(iface.name .. " " .. iface.family .. " " .. iface.addr)
end
end
注意: 在 ESP32-S3 目标上不可用,返回错误。
3. Socket 对象方法
net_bind 和 net_connect 返回的是 socket 对象,支持以下方法。
sock:info([which]) → table
获取套接字信息。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
which | string | nil:基本信息;"peer":对端信息;"socket":本端信息;"tls":TLS 状态(返回 "off"/"connect"/"handshake"/"on" 或错误串;未指定 secure 创建的套接字恒为 "off")。未知取值返回 nil。family/type 在无法识别时为 "unknown" |
返回:
which=nil 时返回:
{
fd = 5, -- 文件描述符
family = "inet", -- "inet" 或 "inet6"
type = "tcp", -- "tcp" 或 "udp"
listening = true, -- 是否为监听套接字
multicast = false -- 是否为多播
}
which="peer" 或 "socket" 时返回:
{
addr = "192.168.1.100", -- IP 地址
port = 8080, -- 端口号
family = "inet" -- "inet" 或 "inet6"
}
示例:
-- 基本信息
for k, v in pairs(sock:info()) do
printh(k .. ": " .. tostring(v))
end
-- 对端地址
local peer = sock:info("peer")
printh("Connected to: " .. peer.addr .. ":" .. peer.port)
-- 本端地址
local me = sock:info("socket")
printh("Local: " .. me.addr .. ":" .. me.port)
sock:cando(send) → boolean
检查套接字是否可读/可写(非阻塞探测)。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
send | boolean | false/nil:检查可读性;true:检查可写性 |
示例:
if sock:cando(false) then
local data = sock:recv()
end
sock:accept() → client_socket, addr, port | false | nil, err
接受 TCP 连接(仅监听套接字可用)。非阻塞,无连接时返回 false。
返回:
- 有连接:新 socket 对象 + 客户端 IP + 客户端端口
- 无连接:
false - 错误:
nil, 错误信息
示例:
local server = net_bind("tcp", 8080)
-- 在 _draw() 循环中
local client, addr, port = server:accept()
if client then
printh("New connection from " .. addr .. ":" .. port)
end
sock:recv([pattern [, prefix]]) → data [, err [, partial]]
接收数据(TCP 套接字)。非阻塞。
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
pattern | string/number | "*l" | "*l":读一行;"*a":读全部;数字:读指定字节数 |
prefix | string | "" | 拼接到结果前面的已有数据 |
返回值(三种情况):
| 情况 | 返回 |
|---|---|
| 成功 | data, nil, nil |
| 超时(无数据) | false, "timeout", partial_data |
| 连接关闭/错误 | nil, "closed"/errmsg, partial_data |
示例:
-- 读一行
local line, err, partial = sock:recv("*l")
-- 读取 1024 字节
local data, err, partial = sock:recv(1024)
-- 读取所有数据
local all, err = sock:recv("*a")
-- 拼接之前的部分数据继续读
local data, err, partial = sock:recv(1024, previous_partial)
sock:recvfrom([size]) → data, addr, port | false | nil, err
接收 UDP 数据报(仅 UDP 套接字可用)。非阻塞。
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
size | number | 4096 | 最大读取字节数(上限 64KB,超限抛 Lua 错误 "EBA") |
返回值:
| 情况 | 返回 |
|---|---|
| 成功 | data, sender_ip, sender_port |
| 无数据 | false |
| 错误 | nil, err |
示例:
local server = net_bind("udp", "0.0.0.0", 9000)
-- 在 _draw() 循环中
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
发送数据(TCP 套接字)。非阻塞。
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
data | string | 必填 | 要发送的数据 |
from | number | 1 | 起始位置(1-based) |
to | number | #data | 结束位置 |
返回值:
| 情况 | 返回 |
|---|---|
| 成功 | next_position, nil, nil(next_position 为下次发送的起始位置) |
| 超时 | false, nil, last_sent_index |
| 错误 | nil, err, last_sent_index |
示例:
-- 简单发送
local sent, err = sock:send("hello\n")
-- 断点续发(发送未完成的剩余部分)
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 -- 超时,下次重试
else
break -- 错误
end
end
sock:sendto(data, addr, port) → size | false | nil, err
发送 UDP 数据报到指定地址。非阻塞。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
data | string | 要发送的数据 |
addr | string | 目标 IP 地址 |
port | number | 目标端口 |
返回值:
| 情况 | 返回 |
|---|---|
| 成功 | sent_bytes(已发送字节数) |
| 超时 | false |
| 错误 | nil, err |
示例:
local server = net_bind("udp", "0.0.0.0", 9000)
server:sendto("hello", "192.168.1.100", 8080)
sock:timeout([value]) → number
设置或获取套接字超时时间。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
value | number | 超时秒数(传入则设置,不传则只读取) |
返回: 当前超时值(秒)。未设置过超时时无返回值(nil);仅当已设置为非负数后才返回该值。
说明: 此超时值由 Copas 调度器参考使用,不直接影响底层套接字(底层始终非阻塞)。
sock:close() → true | nil, err
关闭套接字,释放资源。套接字被 GC 回收时也会自动关闭。
sock:close()
4. Copas 异步调度器
Copas 是基于 Lua 协程的协作式多任务调度器,封装了非阻塞 I/O 操作,让网络代码可以写成同步风格。
引入方式
Copas 定义在 colox_net.lua 中,需要使用 #include 引入:
usemod('net')
#include colox_net.lua
引入后,全局变量 copas、以及辅助函数 net_protect、net_newtry 可用。
net_protect(func) → function
将函数包装为安全调用:由 net_newtry/HTTP 层抛出的 table 形式错误会被转为 (nil, err) 返回;普通字符串错误会继续向上抛出。
local safe_func = net_protect(function(a, b)
-- newtry 类错误不会抛异常,而是返回 nil, errmsg
return do_something(a, b)
end)
local result, err = safe_func(1, 2)
net_newtry(finalizer) → function
创建一个"try"包装器,失败时自动调用 finalizer 清理资源。
local try = net_newtry(function() sock:close() end)
-- 如果 send 失败,自动关闭套接字并抛出错误
try(sock:send("hello"))
核心概念
Copas 通过协程实现异步 I/O:
- 在协程中调用
copas.receive()/copas.send() - 如果操作会阻塞(无数据/缓冲区满),协程自动挂起
- 在主循环
_draw()中调用copas.step(),调度器检查所有套接字状态 - 有就绪事件的套接字,其等待的协程被恢复执行
关键: copas.step() 必须在每帧调用,否则所有网络操作都不会推进。
copas.step() → boolean
执行一轮调度。在每帧 _draw() 中调用。返回 false 表示本轮无事可做。
示例:
function _draw()
copas.step()
end
copas.addthread(func [, ...]) → thread
创建一个新协程并立即开始执行。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
func | function | 协程函数 |
... | any | 传递给 func 的额外参数 |
返回: 协程对象(可用于 copas.removethread())
示例:
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)
移除一个协程,停止其执行并关闭关联套接字。
local thread = copas.addthread(function() ... end)
-- 稍后
copas.removethread(thread)
copas.addserver(server, handler)
注册服务端套接字及其连接处理函数。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
server | socket | net_bind() 创建的服务端套接字 |
handler | function | 新连接的处理函数(接收 client socket 作为参数) |
示例:
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)
说明:
- TCP 服务端:每个新连接自动创建协程运行 handler
- UDP 服务端:直接在协程中运行 handler,通过
copas.receivefrom()/copas.sendto()收发(注意:net_connect("udp",...)创建的套接字已设默认目标,协程内直接copas.send即可)
copas.removeserver(server [, keep_open])
移除已注册的服务端。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
server | socket | 服务端套接字 |
keep_open | boolean | true 不关闭套接字,false(默认)关闭 |
copas.receive(client [, pattern [, part [, timeout]]]) → data, err, partial
异步接收数据(TCP)。协程会在无数据时自动挂起。
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
client | socket | 必填 | TCP 套接字 |
pattern | string/number | "*l" | 同 sock:recv() 的 pattern |
part | string | "" | 已有部分数据 |
timeout | number | 套接字 timeout | 接收超时(秒) |
示例:
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
类似 copas.receive(),但 pattern 为数字时,收到部分数据即返回(不必凑满指定字节数);*l/*a 行为与 receive 完全相同。
适用场景: 流式数据处理,不关心消息边界。
local data, err, partial = copas.receivePartial(client, 1024, nil, 5)
copas.receivefrom(client [, size [, timeout]]) → data, addr, port
异步接收 UDP 数据报。
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
client | socket | 必填 | UDP 套接字 |
size | number | 8192 | 最大读取字节数 |
timeout | number | 套接字 timeout | 超时秒数 |
copas.send(client, data [, from [, to [, timeout]]]) → result, err, last_index
异步发送数据(TCP)。协程会在缓冲区满时自动挂起。
copas.sendto(client, data, ip, port [, timeout]) → result, err
异步发送 UDP 数据报。
copas.sleep(sleeptime)
挂起当前协程指定秒数。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
sleeptime | number | 秒数。< 0 表示无限期休眠(需 wakeup 唤醒) |
copas.addthread(function()
while true do
do_periodic_task()
copas.sleep(10) -- 每 10 秒执行一次
end
end)
copas.wakeup(thread)
唤醒一个正在 copas.sleep() 的协程。
local thread = copas.addthread(function()
copas.sleep(-1) -- 无限期等待
printh("Woken up!")
end)
-- 稍后
copas.wakeup(thread)
copas.finished() → boolean
检查是否所有任务都已完成(没有活跃的读写套接字和休眠协程)。
copas.setErrorHandler(handler)
为当前协程设置错误处理函数。
copas.setErrorHandler(function(msg, co, skt)
printh("Error in coroutine: " .. tostring(msg))
end)
5. HTTP 客户端 (nethttp)
基于 Copas 的 HTTP/1.1 客户端,支持 GET/POST、重定向跟踪、分块传输编码、multipart 响应。
引入方式
usemod('net')
#include colox_net.lua
#include colox_http.lua
引入后,全局变量 nethttp 可用。
nethttp.request(request_or_url [, body [, timeout]]) → result, code, headers, status
发送 HTTP 请求。
简单 GET
local body, code, headers, status = nethttp.request("http://example.com/api")
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
request_or_url | string | URL 字符串(支持 user:pass@host 形式,自动生成 Authorization: Basic 头) |
body | string | POST 请求体(nil 则为 GET) |
timeout | number | 超时秒数 |
返回(字符串 URL 形式):
| 返回值 | 类型 | 说明 |
|---|---|---|
result | string | 响应体内容 |
code | number | HTTP 状态码(200, 404 等) |
headers | table | 响应头 {name=value, ...}(键名统一小写,如 headers["content-length"]) |
status | string | 状态行(如 "HTTP/1.1 200 OK") |
table 请求形式的首返回值为数字
1,响应体需经sink收集。
POST 请求(简单字符串 URL)
local body = '{"key":"value"}'
local result, code = nethttp.request("http://example.com/api", body)
高级请求(table 形式)
local json_body = '{"key":"value"}'
local t = {} -- 响应体收集表
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)
请求表字段:
| 字段 | 类型 | 说明 |
|---|---|---|
url | string | 请求 URL |
method | string | HTTP 方法("GET"、"POST" 等) |
headers | table | 请求头 {name=value} |
source | function | LTN12 source,请求体数据源 |
sink | function | LTN12 sink,响应体目标 |
step | function | LTN12 pump step 函数 |
proxy | string | HTTP 代理地址 |
redirect | boolean | 是否跟随重定向(默认 true;仅 301/302/303/307 且方法为 GET/HEAD 时跟随,最多 5 次) |
connecttimeout | number | 连接超时(秒) |
_on_header | function | 收到响应头后的回调,返回 false 可中断 |
_noclose | boolean | true 保持连接(keep-alive) |
_multipart | table | multipart 响应处理器 |
nethttp.open(host, port) → http_connection
创建 HTTP 连接(低级 API)。通常不需要直接使用,request() 内部调用。连接失败时返回 nil(无错误串)。
常用模式
JSON POST 请求
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)
简单 GET 请求
copas.addthread(function()
local body, code = nethttp.request("http://example.com/data")
if body then
printh("Got: " .. body)
end
end)
股票数据示例
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 客户端 (ws)
基于 Copas 的 WebSocket 客户端(RFC 6455),支持 ws:// 与 wss://(客户端角色)。支持文本/二进制消息、消息分片重组、控制帧(ping/pong/close)、自动回复 pong、关闭握手。客户端发送的帧一律加掩码,符合 RFC 6455 §5.1。
wss://需要固件支持 TLS socket(同net_connect的secure参数,见第 2 节);未编入时ws_connect对wss://快速失败返回tls not compiled。不支持permessage-deflate压缩、服务端角色、自动重连。opts.timeout(秒)是连接/握手/升级请求的整体预算(默认 15s),对 wss 尤其重要。
引入方式
usemod('net')
#include colox_net.lua
#include colox_ws.lua -- 必需(colox_http.lua 非必需,仅与本文其他示例共存时才引入)
引入后,后续代码即可直接调用 ws_connect。握手用的 base64/SHA-1 由宿主全局函数 b64encode/sha1sum 提供(C 实现,见 lua.md),不强依赖 colox_http.lua。
与其它 Copas 网络代码一样,所有
ws:*阻塞调用必须在copas.addthread创建的协程中执行,并由卡带在_draw()中调用copas.step()驱动。colox_ws.lua自身不会启动额外的循环/定时器/线程。
ws_connect(url [, opts]) → ws | nil, err
连接 WebSocket 服务端,完成 RFC 6455 握手。
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
url | string | 必填 | ws://host[:port]/path(端口缺省 80)/ wss://(端口缺省 443) |
opts.headers | table | nil | 额外请求头 {name=value, ...} |
opts.verify_accept | boolean | true | 是否校验 Sec-WebSocket-Accept;默认开启(传 false 显式关闭) |
opts.timeout | number | 15 | 握手整体预算(秒,发送与读响应阶段共用) |
返回: 成功返回 ws 对象;失败返回 nil, err(err 如 "connect failed"、"bad upgrade response"、"bad Sec-WebSocket-Accept" 等)。
说明:
- 握手时强制校验响应头
Upgrade: websocket与Connection: Upgrade(RFC 6455 §4.2.2),不匹配直接失败。 Sec-WebSocket-Accept默认用纯 Lua SHA-1 校验;若需要禁用,传opts.verify_accept = false。
ws:receive() → msg | nil, err
阻塞接收下一条 WebSocket 消息(必须在协程中调用)。
返回:
| 情况 | 返回 |
|---|---|
| 收到消息 | msg, nil,其中 msg = { op = "text"\|"binary"\|"close", data = string }(对端 ping 自动回 pong、pong 静默丢弃,均不上抛) |
| 连接关闭/出错 | nil, err,err ∈ { "closed", "timeout", <协议错误> } |
说明:
op == "close"时,msg.data为对端发送的数值状态码(或nil)。- 自动应答对端的
ping(回复相同 payload 的pong),不作为消息上抛。 - 分片消息会自动重组;分片过程中穿插的控制帧也会被正确处理(RFC 6455 §5.4)。
- 协议错误(RSV 位非零、未知 opcode、服务端发来带掩码的帧等)会发送 1002 关闭帧并返回
nil, "closed"。
ws:send(data [, kind]) → ok | nil, err
发送一条消息。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
data | string | 必填 | 消息内容(非字符串会 tostring) |
kind | string | "text" | "text" 或 "binary" |
返回: true | nil, err。发送超时同样返回 nil, "timeout"(连接视为已断开)。
ws:send_control(kind [, payload]) → ok | nil, err
发送控制帧。
| 参数 | 类型 | 说明 |
|---|---|---|
kind | string | "ping" 或 "pong" |
payload | string | 载荷,最长 125 字节 |
ws:send_control("ping", "hi")
ws:close([code [, reason]]) → ok | nil, err
发送关闭帧并关闭连接(默认状态码 1000)。幂等:重复调用安全。
ws:close(1000, "bye")
ws:isclosed() → boolean
返回连接是否已关闭(已收到/发出关闭帧,或读写出错)。
完整示例
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 解析 (nethttp)
colox_http.lua 内置 URL 解析/构建函数,全部挂在 nethttp 表上(没有独立的 url 全局变量)。
nethttp.parse(url_string [, default]) → table
解析 URL 为组件表。
local parsed = nethttp.parse("http://user:pass@example.com:8080/path?q=1#frag")
-- 结果:
-- {
-- 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
从组件表构建 URL。
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
将相对 URL 解析为绝对 URL。
local abs = nethttp.absolute("http://example.com/dir/page", "../other")
-- → "http://example.com/other"
nethttp.escape(s) → string
URL 编码。
nethttp.escape("hello world!")
-- → "hello%20world%21"
nethttp.unescape(s) → string
URL 解码。
nethttp.unescape("hello%20world%21")
-- → "hello world!"
nethttp.parse_path(path) → table
解析 URL 路径为段列表。
local segments = nethttp.parse_path("/a/b/c")
-- → {"a", "b", "c", is_absolute=1}
nethttp.build_path(parsed [, unsafe]) → string
从段列表构建路径。
nethttp.build_path({"a", "b", "c", is_absolute=1})
-- → "/a/b/c"
8. LTN12 数据流
LTN12(Lua Technical Note 12)是 LuaSocket 定义的数据流模型,coloX 在 colox_http.lua 中实现了完整支持。通过 nethttp.ltn12 访问。
概念
| 概念 | 说明 |
|---|---|
| Source | 数据生产者,每次调用返回一块数据,结束时返回 nil |
| Sink | 数据消费者,接收一块数据,返回成功状态 |
| Filter | 数据转换器,输入一块数据,输出转换后的数据 |
| Pump | 驱动数据从 Source 流向 Sink |
Source
nethttp.ltn12.source.string(s) → source
创建字符串数据源。
local src = nethttp.ltn12.source.string('{"key":"value"}')
nethttp.ltn12.source.empty() → source
创建空数据源。
nethttp.ltn12.source.cat(...) → source
串联多个数据源。
nethttp.ltn12.source.chain(src, filter [, ...]) → source
将数据源通过一个或多个过滤器串联。
nethttp.ltn12.source.file(handle) → source
创建文件数据源(如果平台支持文件 I/O)。
Sink
nethttp.ltn12.sink.table([t]) → sink, t
创建表收集器,将所有数据块收集到一个表中。
local t = {}
local sink = nethttp.ltn12.sink.table(t)
-- ... pump 数据到 sink
local full_data = table.concat(t)
nethttp.ltn12.sink.null() → sink
创建丢弃所有数据的 sink。
nethttp.ltn12.sink.file(handle) → sink
创建文件写入 sink。
nethttp.ltn12.sink.chain(filter, sink [, ...]) → sink
将数据通过过滤器后送入 sink。
Filter
nethttp.ltn12.filter.cycle(low, ctx, extra) → filter
创建循环过滤器。
nethttp.ltn12.filter.chain(...) → filter
链式过滤器。
Pump
nethttp.ltn12.pump.all(source, sink [, step]) → result, err
将所有数据从 source 泵送到 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
泵送一块数据。
9. 综合示例
示例 1:TCP Echo 服务端
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
示例 2:UDP 数据报收发
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
示例 3:HTTP GET 请求
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
示例 4:HTTP POST JSON 数据
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
示例 5:TCP 客户端连接
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 秒收发超时(不设则近似永不超时,下面的 timeout 分支不会触发)
copas.addthread(function()
-- 发送数据(连接非阻塞,首次发送时才真正完成握手)
copas.send(client, "Hello from coloX\n")
-- 连接建立后查看对端信息
local peer = client:info("peer")
if peer then
printh("Connected to " .. peer.addr .. ":" .. peer.port)
end
-- 持续接收
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") -- 心跳
end
end
client:close()
end)
function _draw()
copas.step()
end
示例 6:DNS 解析与网络接口查询
coloX-16
version 1
__lua__
usemod('net')
-- DNS 解析
local addrs = net_resolve("example.com")
if addrs then
for _, a in ipairs(addrs) do
printh(a.family .. " → " .. a.addr)
end
end
-- 本机网络接口
local ifaces = net_getinf()
if ifaces then
for _, ifa in ipairs(ifaces) do
printh(ifa.name .. " " .. ifa.family .. " " .. ifa.addr)
end
end
10. 完整 API 索引
全局函数
| 函数 | 返回 | 说明 |
|---|---|---|
net_bind([type], [addr], port [, backlog]) | socket | nil, err | 创建服务端套接字 |
net_connect([type], addr, port [, ttl [, secure]]) | socket | nil, err | 连接远程服务器(secure=true 为 TLS) |
net_select(read_tbl, write_tbl) | ready_r, ready_w [, err] | 检查套接字就绪状态 |
net_resolve(name) | table | nil, err | DNS 解析 |
net_getinf() | table | nil, err | 获取网络接口列表 |
Socket 方法
| 方法 | 返回 | 说明 |
|---|---|---|
sock:info([which]) | table | 套接字信息 |
sock:cando(send) | boolean | 检查可读/可写 |
sock:accept() | socket, addr, port | false | 接受 TCP 连接 |
sock:recv([pattern [, prefix]]) | data [, err, partial] | 接收 TCP 数据 |
sock:recvfrom([size]) | data, addr, port | false | 接收 UDP 数据报 |
sock:send(data [, from, to]) | idx, nil, nil | false/nil, ... | 发送 TCP 数据 |
sock:sendto(data, addr, port) | size | false | nil, err | 发送 UDP 数据报 |
sock:timeout([value]) | number | 设置/获取超时 |
sock:close() | true | nil, err | 关闭套接字 |
Copas 方法(需 #include colox_net.lua)
| 方法 | 说明 |
|---|---|
net_protect(func) | 安全包装函数(捕获异常转 (nil, err)) |
net_newtry(finalizer) | 创建 try 包装器(失败自动清理) |
copas.step() | 执行一轮调度 |
copas.addthread(func [, ...]) | 创建协程 |
copas.removethread(thread) | 移除协程 |
copas.addserver(server, handler) | 注册服务端 |
copas.removeserver(server [, keep_open]) | 移除服务端 |
copas.receive(client [, pattern [, part [, timeout]]]) | 异步接收 TCP |
copas.receivePartial(client [, pattern [, part [, timeout]]]) | 异步部分接收 |
copas.receivefrom(client [, size [, timeout]]) | 异步接收 UDP |
copas.send(client, data [, from [, to [, timeout]]]) | 异步发送 TCP |
copas.sendto(client, data, ip, port [, timeout]) | 异步发送 UDP |
copas.sleep(sleeptime) | 挂起协程 |
copas.wakeup(thread) | 唤醒协程 |
copas.finished() | 检查是否完成 |
copas.setErrorHandler(handler) | 设置错误处理 |
copas.autoclose | 自动关闭标志(默认 true) |
HTTP 方法(需 #include colox_http.lua)
| 方法 | 说明 |
|---|---|
nethttp.request(req_or_url [, body [, timeout]]) | 发送 HTTP 请求 |
nethttp.open(host, port [, create [, timeout]]) | 创建 HTTP 连接 |
nethttp.TIMEOUT | 默认超时(60 秒) |
nethttp.PORT | 默认端口(80) |
nethttp.USERAGENT | User-Agent("coloX") |
WebSocket 方法(需 #include colox_net.lua 与 colox_ws.lua;colox_http.lua 可选)
| 方法 | 说明 |
|---|---|
ws_connect(url [, opts]) | 连接 ws 服务端并完成握手,返回 ws \| nil, err |
ws:receive() | 阻塞接收一条消息,返回 msg \| nil, err |
ws:send(data [, kind]) | 发送文本/二进制消息,kind ∈ "text"(默认)/"binary" |
ws:send_control(kind [, payload]) | 发送 ping/pong 控制帧,载荷 ≤125 字节 |
ws:close([code [, reason]]) | 发送关闭帧并关闭连接(默认 1000),幂等 |
ws:isclosed() | 连接是否已关闭 |
URL 方法
| 方法 | 说明 |
|---|---|
nethttp.parse(url [, default]) | 解析 URL |
nethttp.build(parsed) | 构建 URL |
nethttp.absolute(base, relative) | 解析绝对 URL |
nethttp.escape(s) | URL 编码 |
nethttp.unescape(s) | URL 解码 |
nethttp.parse_path(path) | 解析路径 |
nethttp.build_path(parsed [, unsafe]) | 构建路径 |
LTN12 方法
| 方法 | 说明 |
|---|---|
nethttp.ltn12.source.string(s) | 字符串数据源 |
nethttp.ltn12.source.empty() | 空数据源 |
nethttp.ltn12.source.cat(...) | 串联数据源 |
nethttp.ltn12.source.chain(src, f, ...) | 链式数据源 |
nethttp.ltn12.source.file(handle) | 文件数据源 |
nethttp.ltn12.sink.table([t]) | 表收集器 |
nethttp.ltn12.sink.null() | 丢弃 sink |
nethttp.ltn12.sink.file(handle) | 文件 sink |
nethttp.ltn12.sink.chain(f, snk, ...) | 链式 sink |
nethttp.ltn12.filter.cycle(low, ctx, extra) | 循环过滤器 |
nethttp.ltn12.filter.chain(...) | 链式过滤器 |
nethttp.ltn12.pump.all(src, snk [, step]) | 泵送全部数据 |
nethttp.ltn12.pump.step(src, snk) | 泵送一块数据 |
11. 平台差异(Windows)
Windows 平台与其他平台的行为差异:
| 项 | Windows 表现 | 说明 |
|---|---|---|
net_getinf | 返回 nil,"ENS" | 暂未实现(ESP32/Android 同) |
TLS(secure=true) | 可用 | 证书校验走 Windows 系统证书库(其他桌面平台用系统 CA,语义一致) |
net_select 单集合 socket 数 | 上限 64,超出报 Lua 错误 "EFD" | 其他平台上限 1024 且静默截断;Windows 主动报错而非丢事件 |
| 非阻塞 connect 失败 | 失败的连接同样经 net_select 报"可写"(except 集已并入 write 结果),send/recv 返回具体错误 | 与 posix "可写后查错误"的 Copas 语义一致 |
| 错误报文 | WSA 错误码映射的等价文案(如 "connection refused"),未映射项为 "wsa error <n>" | 与其他平台文案等价,仅未映射码带 wsa error 前缀 |
| 本机防火墙注意 | 连接"未被监听的端口"可能既不可写也无错误(RST 被防火墙吞掉,卡在 in-flight)——属系统行为,非模块缺陷 | 测试拒绝路径时勿用裸端口,用对端主动 RST 的场景 |