To handle connections in Thousand Island, you must create a module that implements the ThousandIsland.Handler behaviour. The easiest way to do this is by using the use ThousandIsland.Handler macro, which provides a GenServer-based implementation.
When using the macro, your handler's state must be managed in a {socket, state} tuple format for all GenServer callbacks (like handle_call, handle_cast, and handle_info).
Lifecycle Overview
handle_connection(socket, state): Called after the initial connection setup (e.g., TLS handshake).- Return
{:close, state} to terminate the connection. - Return
{:continue, state} to keep the connection open and wait for data asynchronously.
handle_data(data, socket, state): Called when the client sends data (only if handle_connection returned {:continue, ...}).handle_close(socket, state): Called when the remote end closes the connection.handle_error(reason, socket, state): Called on socket errors or handshake failures.handle_shutdown(socket, state): Called when the server itself is shutting down.handle_timeout(socket, state): Called when no data is received within the configured read_timeout.
defmodule ExampleHandler do
use ThousandIsland.Handler
@impl ThousandIsland.Handler
def handle_connection(socket, state) do
ThousandIsland.Socket.send(socket, "Hello, World!")
{:close, state}
end
@impl ThousandIsland.Handler
def handle_data(data, socket, state) do
ThousandIsland.Socket.send(socket, data)
{:continue, state}
end
end