0Pricing
Lua Academy · Lesson

Building a Server

Accept incoming connections.

Server Lifecycle

A TCP server binds to an address, listens for connections, then loops accepting and serving clients.

In LuaSocket you create a master with socket.tcp(), turn it into a listening server with bind/listen, and pull clients off the queue with accept.

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

Binding to a Port

server:bind(host, port) reserves a local address. Use "*" or "0.0.0.0" to accept connections on every interface, or "127.0.0.1" for local only.

Bind fails with "address already in use" if another process holds the port.

server:setoption("reuseaddr", true)
local ok, err = server:bind("*", 8080)
if not ok then error("bind 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