How does the LuaSocket server handle multiple requests at the same time?

The problem is that my Lua server cannot accept multiple requests at the same time. I tried to process every client message in its coroutine, but this did not seem to succeed.

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

This code does not seem to actually receive more than one client message at a time. What is wrong with this method? Thanks for helping.

+1
source share
2 answers

You cannot create true simultaneous processing only with coroutines - coroutines are designed for joint multitasking. Only one coroutine is executed at a time.

The code you wrote is no different from calling GiveMessage() in a loop directly. You need to write a coroutine manager and find a reasonable reason for exiting GiveMessage() for this approach to work.

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

  • Create several forks of your server, process operations in coroutines in each fork. Manage coroutines with either Copas or lua-ev or with a homegrown dispatcher, there’s nothing wrong with that. I recommend this way.

  • Use Lua states instead of coroutines, keep a state pool, a thread pool of a working operating system, and a task queue. Complete each task in a free Lua state with a free workflow. Some low level coding is required and randomly.

  • Look for existing more specialized solutions - there are several, but to advise that I need to know better which server you are writing.

  • Whatever you choose, avoid using the same Lua state from multiple threads at the same time. (Maybe with the right amount of coding, but a bad idea.)

+4
source

AFAIK coroutines do not play well with luaSocket out of the box. But there is a copas that you can use.

-1
source

Source: https://habr.com/ru/post/1486581/


All Articles