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)
endAll lessons in this course
- TCP Basics
- Building a Client
- Building a Server
- HTTP Requests