主题
UDP 通信例程 3:对端存活探测(发 PING 等 PONG)
这一页只讲这一个例程。同组其余例程、以及这个库的函数说明都在 05-06-udp。
适用:同上 | 依赖模块:udp timer plc | 难度:★☆☆
场景:想知道某台设备在不在线,发 PING,自己计时 3 秒等 PONG。
完整代码(可直接下载运行):
lua
udps = udp.creat(6000, "0.0.0.0")
got = false
udps:reg(udp.RECVDATA, function(ip, port, data)
if data == "PONG" then got = true end
end)
udps:start()
udps:send("192.168.1.100", 6000, "PING")
timer.start(3000, function()
print(got and "对端在线" or "3 秒没回包")
end, true) -- 第三个参数 true = 单次定时器要点:
- UDP 无连接、无
is_linked,存活只能靠"发查询 + 计时等回包"。 timer.start(ms, fn, true)的true表示只触发一次(单次定时器)。
验证方法:
- 对端收到
PING回PONG→ 打印"对端在线"。 - 对端关机 → 3 秒后打印"3 秒没回包"。
注意事项:
udp没有close方法,要停止收包只能把对象变量置nil等 GC。- 收包线程由
start驱动,没start收不到。