Non-Blocking I/O with luasocket
Use luasocket in non-blocking mode integrated with a coroutine scheduler.
Non-Blocking I/O with luasocket is a free Lua Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is luasocket?
luasocket is a Lua library providing TCP/UDP sockets, HTTP, FTP, and SMTP clients. By default it is blocking; non-blocking mode enables async I/O.
Installing luasocket
Install via LuaRocks: luarocks install luasocket. Require it in your script.
local socket = require("socket")
local tcp = socket.tcp()Creating a TCP Socket
Create a TCP client socket and connect to a server.
local tcp = socket.tcp()
tcp:connect("example.com", 80)
tcp:send("GET / HTTP/1.0\r\nHost: example.com\r\n\r\n")
local response = tcp:receive("*a")
tcp:close()
print(response:sub(1, 200))Non-Blocking Mode
Set the socket to non-blocking with tcp:settimeout(0). Reads/writes return immediately with a timeout error if no data is ready.
tcp:settimeout(0) -- non-blocking
local data, err = tcp:receive(1024)
if err == "timeout" then
-- no data yet, try again later
elseif data then
print("Got:", data)
endCoroutine Integration
Combine non-blocking sockets with coroutines: yield when data is not ready, and resume the coroutine when the selector indicates readiness.
local function readAsync(sock)
while true do
local data, err = sock:receive(1024)
if data then return data end
if err ~= "timeout" then error(err) end
coroutine.yield() -- let other tasks run
end
endsocket.select
socket.select(readSet, writeSet, timeout) returns sets of sockets ready for I/O — the foundation of a proper event loop.
local readable, writable = socket.select({sock1, sock2}, nil, 0.1)
for _, s in ipairs(readable) do
local data = s:receive(1024)
-- handle data
endHTTP Client
luasocket includes a high-level HTTP module for simple requests.
local http = require("socket.http")
local body, code = http.request("http://example.com")
print(code, #body)UDP Sockets
UDP is connectionless. Use socket.udp() for datagram-based communication.
local udp = socket.udp()
udp:setsockname("*", 0)
udp:sendto("hello", "127.0.0.1", 9999)
local data = udp:receive()
udp:close()Timeouts
Set a timeout with :settimeout(seconds). A timeout of 0 is non-blocking; a positive number allows partial blocking; nil means block indefinitely.
Error Handling Pattern
luasocket functions return nil + error string on failure. Always check the second return value.
local ok, err = tcp:connect("host", 80)
if not ok then
error("Connection failed: " .. tostring(err))
endOpenResty Alternative
For production non-blocking I/O in LuaJIT, OpenResty's cosockets are far more capable and performant. Use luasocket for standalone scripts and simple tools.
Non-Blocking Question
What does tcp:settimeout(0) do?
Recap: Non-Blocking I/O
Use settimeout(0) for non-blocking sockets and socket.select for I/O multiplexing. Combine with coroutines: yield on timeout, resume when data is ready. For high-performance async I/O, prefer OpenResty or luv.
Frequently asked questions
Is the “Non-Blocking I/O with luasocket” lesson free?
Yes — the full text of “Non-Blocking I/O with luasocket” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.
What will I learn in “Non-Blocking I/O with luasocket”?
Use luasocket in non-blocking mode integrated with a coroutine scheduler. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Non-Blocking I/O with luasocket” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Building a Simple Event Loop
- Async/Await with Coroutines
- Promise-Like Patterns
- Non-Blocking I/O with luasocket