UDP 用于无连接报文通信,适合局域网发现、设备广播、轻量状态上报等场景。当前版本支持 UDP 监听和 UDP 客户端发送。
udp = net.listen({ type:'udp', bind:'127.0.0.1:9001', on_message:fn(data, addr){ udp.send('echo:' + data, addr.addr) }, on_error:fn(err){ println(err) } })
udp = net.connect({ type:'udp', host:'127.0.0.1', port:9001 }) udp.send('hello') udp.close()
net.listen({type:'udp'}):
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| type | string | 是 | 无 | 固定为 udp |
| bind | string | 是 | 无 | 本地绑定地址,格式为 host:port |
| on_message | fn | 否 | 无 | 收到报文后调用,参数为 data, addr |
| on_error | fn | 否 | 无 | 后台任务出错时调用,参数为 err |
net.connect({type:'udp'}):
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| type | string | 是 | 无 | 固定为 udp |
| host | string | 是 | 无 | 默认远端主机名或 IP |
| port | int | 是 | 无 | 默认远端端口,范围 0..65535 |
返回 UdpSocket 对象。
| 字段/方法 | 类型 | 说明 |
|---|---|---|
| addr | string | 本地 socket 地址 |
| type | string | 固定为 udp |
| send(data) | fn | 向默认远端发送字符串,返回写入字节数 |
| send(data, addr) | fn | 向指定 host:port 发送字符串,返回写入字节数 |
| close() | fn | 关闭 socket,返回 true |
net.listen({type:'udp'}) 通过 on_message(data, addr) 接收报文,没有同步 read() 方法。
addr 是对象,包含 ip、port、addr 字段;回发时可使用 addr.addr。
send(data) 时必须传第二个目标地址;客户端模式可以省略目标地址。