calog/examples/scripts/libraries/net.lua

35 lines
1.4 KiB
Lua

-- Showcase the calog net library over loopback with UDP datagrams: a spawned
-- "lua" listener task binds a fixed high port and blocks in udpRecvFrom, while
-- the main context opens an ephemeral socket and sends one datagram to it. The
-- listener's blocking recv runs on its own task thread, so the main thread stays
-- free to send. A short delay lets the datagram arrive and print before we exit.
-- Run: bin/calog examples/scripts/libraries/net.lua
local PORT = 47651
-- The listener runs in its own context/thread, so its blocking udpRecvFrom does
-- not stall the main script. It prints the payload and sender it received.
local listenerCode = string.format([[
local sock = udpOpen(%d)
calogPrint("listener bound on port", %d)
local packet = udpRecvFrom(sock, 1024)
calogPrint("listener received:", packet.data, "from", packet.host .. ":" .. packet.port)
udpClose(sock)
]], PORT, PORT)
local listener = taskSpawn("lua", listenerCode)
calogPrint("spawned listener handle:", listener)
-- Give the listener a beat to bind its socket before we transmit.
timeSleep(200)
local sender = udpOpen(0)
local sent = udpSendTo(sender, "127.0.0.1", PORT, "hello over udp")
calogPrint("sender transmitted", sent, "bytes to 127.0.0.1:" .. PORT)
udpClose(sender)
-- Let the datagram land and the listener print, then tear everything down.
timerAfter(300, function()
taskClose(listener)
calogExit(0)
end)