TCP Basics
Connect and send data.
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