Copas + Lua-WebSockets: Building a WebSocket Server in Lua
A practical guide to building a WebSocket server in Lua using Copas and lua-websockets, including connection handling, receiving messages, responding to clients, and deploying the server.
Ashwin Mehta
7 min read

Building a WebSocket Server in Lua with Copas and lua-websockets
Lua is lightweight, fast, and widely used in applications where performance and simplicity matter. If you're building real-time features with Lua, you'll eventually need a way to maintain persistent connections between your application and its clients.
WebSockets are a great fit for this. They allow clients and servers to exchange messages over a single, long-lived connection without repeatedly making HTTP requests.
In this tutorial, we'll build a simple WebSocket server using Copas and lua-websockets. You'll learn how to accept client connections, receive messages, send responses, handle multiple clients, and deploy your server.
We'll also explore how PieSocket can simplify real-time communication when you need managed WebSocket infrastructure without maintaining your own WebSocket servers.
What are Copas and lua-websockets?
Before writing the server, let's understand the two libraries.
- Copas: A coroutine-based dispatcher for Lua networking. It allows applications to handle multiple connections without blocking the entire application while waiting for network operations.
- lua-websockets: A Lua library that implements the WebSocket protocol and provides server and client implementations, including a Copas-based backend.
Together, they make it possible to build a lightweight WebSocket server without implementing the WebSocket handshake and message framing yourself.
If you'd rather avoid managing WebSocket infrastructure, PieSocket provides a managed WebSocket service that handles connection management and real-time message delivery for your applications.
Installing the dependencies
You'll need LuaRocks to install the required libraries.
Install Copas:
luarocks install copas
Install lua-websockets:
luarocks install lua-websockets
The libraries use LuaSocket for networking. Depending on your Lua environment, you may also need LuaSec and other dependencies.
Creating your first WebSocket server
Create a file named server.lua.
We'll start with a simple echo server. Whenever a client sends a message, the server will send the same message back.
local copas = require("copas")
local websocket = require("websocket")
local port = tonumber(os.getenv("PORT")) or 8080
local server = websocket.server.copas.listen({
port = port,
interface = "0.0.0.0",
default = function(ws)
print("Client connected")
while true do
local message = ws:receive()
if not message then
print("Client disconnected")
ws:close()
return
end
print("Received:", message)
ws:send(message)
end
end
})
print("WebSocket server listening on port " .. port)
copas.loop()
Let's understand what's happening:
- websocket.server.copas.listen() starts a WebSocket server using Copas.
- port specifies the listening port.
- interface = "0.0.0.0" allows the server to accept connections through its available network interfaces.
- default defines the handler for connections that don't request a specific WebSocket subprotocol.
- ws:receive() waits for an incoming message.
- ws:send() sends a message back to the connected client.
- copas.loop() starts the event loop that handles incoming connections.
One important detail: default belongs directly in the configuration table, not inside protocols. The protocols table is used when registering handlers for specific WebSocket subprotocols.
Connecting from a browser
Now that the server is running, let's connect to it from JavaScript.
You can use the browser's built-in WebSocket API.
const socket = new WebSocket("ws://localhost:8080");
socket.onopen = () => {
console.log("Connected to Lua WebSocket server");
socket.send("Hello from JavaScript!");
};
socket.onmessage = (event) => {
console.log("Server response:", event.data);
};
socket.onerror = (error) => {
console.error("WebSocket error:", error);
};
socket.onclose = () => {
console.log("Connection closed");
};
If everything is configured correctly, you should see the server receive the message and send it back.
Browser console:
Connected to Lua WebSocket server
Server response: Hello from JavaScript!
Lua terminal:
WebSocket server listening on port 8080
Client connected
Received: Hello from JavaScript!
Testing your WebSocket connection
Once your WebSocket server is running, you'll want to verify that clients can connect and exchange messages correctly.
Instead of writing a separate test client, you can use the PieHost WebSocket Tester.
It lets you:
- Connect to a WebSocket server using its URL.
- Send custom messages to the server.
- Receive and inspect incoming messages.
- Debug WebSocket connections directly from your browser.
For our example, enter:
ws://localhost:8080
Click Connect, send Hello from WebSocket Tester!, and check whether your Lua server echoes the message back.
It's a convenient way to test WebSocket endpoints during development without building a dedicated frontend.
Handling multiple clients
One advantage of using Copas is that you don't need to manually create a separate operating-system thread for every client.
Each incoming WebSocket connection gets its own handler execution. Copas manages network operations cooperatively, allowing other connections to make progress while one handler waits for network activity.
For example, you could maintain a collection of connected clients:
local clients = {}
local function broadcast(message)
for ws in pairs(clients) do
local ok = pcall(function()
ws:send(message)
end)
if not ok then
clients[ws] = nil
end
end
end
Inside your connection handler, register clients when they connect:
default = function(ws)
clients[ws] = true
while true do
local message = ws:receive()
if not message then
clients[ws] = nil
ws:close()
return
end
broadcast(message)
end
end
This is a basic broadcasting implementation. For production applications, you'll also want proper error handling, connection cleanup, authentication, and protection against slow or disconnected clients.
As your application grows, managing thousands of persistent connections, message delivery, scaling, and server availability can become increasingly complex.
This is where a managed WebSocket service like PieSocket can help.
Using PieSocket for managed real-time communication
Building your own WebSocket server gives you complete control over connection handling and message processing. However, it also means you're responsible for infrastructure, scaling, connection management, and reliability.
PieSocket provides managed WebSocket infrastructure, allowing you to focus on application logic instead of operating WebSocket servers.
With PieSocket, you can:
- Establish persistent WebSocket connections between clients and your application.
- Publish real-time messages to connected clients.
- Build chat applications, live notifications, dashboards, and multiplayer experiences.
- Scale real-time communication without managing your own WebSocket server fleet.
- Integrate real-time messaging into applications written in different programming languages.
You can use Lua for your application backend and PieSocket as the real-time messaging layer.
Connecting to PieSocket from JavaScript
For example, your frontend can establish a connection using the PieSocket WebSocket endpoint.
const socket = new WebSocket(
"wss://free.blr2.piesocket.com/v3/1?api_key=YOUR_API_KEY¬ify_self=1"
);
socket.onopen = () => {
console.log("Connected to PieSocket");
socket.send(JSON.stringify({
event: "message",
data: "Hello from Lua application!"
}));
};
socket.onmessage = (event) => {
console.log("Received:", event.data);
};
socket.onclose = () => {
console.log("Connection closed");
};
Replace the example API key and channel with the values from your PieSocket account. Use the appropriate endpoint and authentication configuration for your project.
Your Lua backend can publish messages to PieSocket using its supported REST API or SDK integration, while connected clients receive messages through their WebSocket connections.
This architecture separates your application logic from real-time message delivery.
For implementation details, visit the PieSocket documentation.
Deploying your Lua WebSocket server
If you're deploying your own Lua WebSocket server, you'll need some additional configuration.
A few things to remember:
- Listen on 0.0.0.0 rather than 127.0.0.1 so external connections can reach your application.
- Use the port supplied by your hosting platform through an environment variable such as PORT.
- Make sure your hosting provider allows persistent WebSocket connections.
- Configure a reverse proxy if your deployment requires one.
- Use wss:// for secure WebSocket connections in production.
If you're deploying behind a reverse proxy such as Nginx, the proxy can terminate TLS on port 443 and forward WebSocket traffic to your Lua server.
For example:
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
}
Your clients can then connect using:
const socket = new WebSocket("wss://ws.example.com");
The public endpoint uses secure WebSockets, while the Lua application handles the connection internally.
If you choose PieSocket instead, you don't need to deploy and maintain this WebSocket server infrastructure yourself. Your application can connect to PieSocket's managed endpoints.
Common issues to check
If your server starts but clients cannot connect, check these things first:
- Wrong listening interface: Make sure you're listening on 0.0.0.0 when external clients need to connect.
- Incorrect port: Check that your application listens on the port provided by your hosting environment.
- Incorrect handler configuration: Keep default at the top level of the configuration table.
- Reverse proxy configuration: Make sure the proxy forwards the WebSocket Upgrade and Connection headers.
- TLS mismatch: Use wss:// when connecting through an HTTPS endpoint, and make sure TLS is configured correctly at the proxy or server.
You can also check server logs to confirm whether the connection handler is being executed.
Conclusion
With Copas and lua-websockets, you can build a functional WebSocket server in Lua without implementing the WebSocket protocol yourself.
This is a good starting point for building chat applications, live notifications, multiplayer features, and other real-time services.
However, building and maintaining your own WebSocket infrastructure isn't always necessary. If you want managed connections, scalable message delivery, and less infrastructure to maintain, PieSocket is worth exploring.
Whether you choose to build your own WebSocket server or use a managed service, Lua can remain at the heart of your application logic.


Comments
No comments yet. Questions and corrections are welcome.