Lua Academy · Lesson

Non-Blocking I/O with luasocket

Use luasocket in non-blocking mode integrated with a coroutine scheduler.

Lesson 4 of 413 steps

Non-Blocking I/O with luasocket is a free Lua Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

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)
end

Coroutine 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
end

socket.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
end

HTTP 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))
end

OpenResty 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.

Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “Non-Blocking I/O with luasocket” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “Non-Blocking I/O with luasocket”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

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

  1. Building a Simple Event Loop
  2. Async/Await with Coroutines
  3. Promise-Like Patterns
  4. Non-Blocking I/O with luasocket
← Back to Lua Academy