Lua Academy · Lesson

TCP Basics

Connect and send data.

Lesson 1 of 413 steps

TCP Basics is a free Lua Academy lesson on CoddyKit. This is lesson 1 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 the de-facto networking library for Lua. It exposes raw TCP and UDP sockets plus higher-level helpers for HTTP, SMTP and FTP.

It is an external C module, so it is not part of stock Lua. You install it via LuaRocks and load it with require.

None of the snippets in this course run on a plain playground because they touch the network.

local socket = require("socket")
print(socket._VERSION)

Creating a TCP Socket

The core object is the TCP master socket, created with socket.tcp(). A fresh master is unconnected and unbound.

From a master you can either connect (turning it into a client object) or bind+listen (turning it into a server object).

Most calls return either a value or nil plus an error string, so always capture both.

local socket = require("socket")
local tcp, err = socket.tcp()
if not tcp then error(err) end

The Address Family

TCP works over IPv4 or IPv6. socket.tcp() picks the family lazily, while socket.tcp4() and socket.tcp6() force one.

Use socket.dns.toip(host) to resolve a hostname to a numeric address before connecting if you need explicit control.

local socket = require("socket")
local ip, info = socket.dns.toip("example.com")
print(ip)

Connecting to a Host

conn:connect(host, port) performs the TCP three-way handshake. On success it returns 1; on failure it returns nil and an error message such as "connection refused" or "timeout".

The convenience function socket.connect(host, port) creates a socket and connects in one call.

local socket = require("socket")
local conn, err = socket.connect("example.com", 80)
if not conn then print("failed:", err) end

Sending Data

conn:send(data) writes bytes to the socket. It returns the index of the last byte sent. With a blocking socket this is usually the full length of data.

TCP is a byte stream, not a message protocol, so a single send may be split or merged across the wire. You must frame your own messages.

local request = "GET / HTTP/1.0\r\n\r\n"
local sent, err = conn:send(request)
print("bytes sent:", sent)

Receiving Data

conn:receive(pattern) reads from the stream. The default pattern "*l" reads one line without the newline. "*a" reads until the connection closes.

You can also pass a number to read exactly that many bytes. On error it returns nil, an error string, and any partial data received.

local line, err = conn:receive("*l")
local chunk = conn:receive(512)
local all = conn:receive("*a")

Closing the Connection

Always call conn:close() when finished to release the file descriptor and send a TCP FIN.

You can half-close with conn:shutdown("send") to signal end-of-stream while still reading the peer's response. This is handy for request/response protocols using "*a".

conn:shutdown("send")
local reply = conn:receive("*a")
conn:close()

Timeouts Matter

By default sockets block forever. conn:settimeout(seconds) bounds how long a call waits. A value of 0 makes the socket non-blocking.

When a timeout fires, the call returns nil and the string "timeout". Always set a timeout in production to avoid hung connections.

conn:settimeout(5)
local data, err = conn:receive("*l")
if err == "timeout" then print("too slow") end

TCP vs UDP

TCP is connection-oriented, ordered, and reliable: bytes arrive once and in order, at the cost of handshakes and retransmits.

UDP (socket.udp()) is connectionless and unreliable but lightweight, good for telemetry or games. This course focuses on TCP because it underpins HTTP.

Partial Sends and Loops

On non-blocking sockets, send may transmit only part of your buffer. It returns nil, "timeout", and the index of the last byte written so far.

A robust sender loops, resuming from the byte after the last one sent until the whole buffer is flushed.

local i = 1
while i <= #data do
  local sent, err, last = conn:send(data, i)
  i = (sent or last) + 1
  if err and err ~= "timeout" then break end
end

Inspecting the Connection

conn:getpeername() returns the remote IP and port, while conn:getsockname() returns the local end. These help with logging and debugging.

conn:setoption("keepalive", true) and conn:setoption("tcp-nodelay", true) tune the underlying socket behaviour.

local ip, port = conn:getpeername()
print("connected to", ip, port)
conn:setoption("tcp-nodelay", true)

Quick Check

Test your understanding of TCP receive semantics.

Recap

You met LuaSocket's TCP master object, learned to create, connect, send, receive, and close sockets, and saw how timeouts and half-close shape behaviour.

Remember TCP is a byte stream, every call may return nil, err, and a production socket always sets a timeout. Next you will assemble these pieces into a working client.

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 “TCP Basics” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “TCP Basics”, 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 “TCP Basics”?

Connect and send data. 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 1 of 4.

How long does the “TCP Basics” 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. TCP Basics
  2. Building a Client
  3. Building a Server
  4. HTTP Requests
← Back to Lua Academy