How can a LuaSocket server handle several requests simultaneously?

2k views Asked by At

The problem is the inability of my Lua server to accept multiple request simultaneously. I attempted to make each client message be processed in its on coroutine, but this seems to have failed.

while true do
local client = server:accept()
coroutine.resume(coroutine.create( function()
GiveMessage( client )
end ) )
end

This code seems to not actually accept more than one client message at the same time. What is wrong with this method? Thank you for helping.

2

There are 2 answers

0
Alexander Gladysh On BEST ANSWER

You will not be able to create true simultaneous handling with coroutines only — coroutines are for cooperative multitasking. Only one coroutine is executed at the same time.

The code that you've wrote is no different from calling GiveMessage() in a loop directly. You need to write a coroutine dispatcher and find a sensible reason to yield from GiveMessage() for that approach to work.

There are least three solutions, depending on the specifics of your task:

  • Spawn several forks of your server, handle operations in coroutines in each fork. Control coroutines either with Copas or with lua-ev or with home-grown dispatcher, nothing wrong with that. I recommend this way.

  • Use Lua states instead of coroutines, keep a pool of states, pool of worker OS threads and a queue of tasks. Execute each task in a free Lua state with a free worker thread. Requires some low-level coding and is messier.

  • Look for existing more specialized solutions — there are several, but to advice on that I need to know better what kind of server you're writing.

  • Whatever you choose, avoid using single Lua state from several threads at the same time. (It is possible, with the right amount of coding, but a bad idea.)

1
jpjacobs On

AFAIK coroutines don't play nice with luaSocket out-of-the-box. But there is Copas you can use.