Ever wanted to make a network server in Lua?

You have come to the right place, after much experimentation on Tethys and Mailcatch.

When it comes down to how you can do a sockets server you have those options:

  • A single process with lua coroutines. The main thread will handle the server socket, when accept’ing connections it starts a new coroutine to handle it. A coroutine scheduler is necessary to yield while waiting on sockets. Such a scheduler could be Copas or LOOP. I will write about it later but I have found this way to choke when handling many connections/seconds
  • A forking server. The main process handles the server socket, when accept’ing connections it forks a new process to handle it. This is quite easy to write using lua posix or some more specialized libs (I will release one that wraps it up nicely someday).
  • A single process server with multithreading. Lua does not do multithread but there are modules out there to do it. The most prominent one being Lua Lanes.

I have experienced with all three (in this order) and settled for multithreading using Lanes with a twist (it does not spawn a new thread for each connection it uses a pool of pre-existing ones) because it gave me, by far, the best performance.

In my next posts I will explain those three methods and how to implement them easily in Lua.