0Pricing
Lua Academy · Lesson

Building a Client

Request data from a server.

Client Lifecycle

A TCP client follows a clear lifecycle: create a socket, connect to a server, exchange data, then close.

In LuaSocket each step is one method call, and each can fail. A well-written client checks every return value and cleans up its socket on any error path.

local socket = require("socket")
local client = assert(socket.tcp())

Connecting Safely

Set a connect timeout before calling connect so a dead host does not hang your program. A few seconds is typical.

If connect returns nil, log the error and abort. Never assume the handshake succeeded.

client:settimeout(5)
local ok, err = client:connect("127.0.0.1", 8080)
if not ok then
  client:close()
  error("connect failed: " .. err)
end

All lessons in this course

  1. TCP Basics
  2. Building a Client
  3. Building a Server
  4. HTTP Requests
← Back to Lua Academy