开发者

How can a LuaSocket server handle several requests simultaneously?

开发者 https://www.devze.com 2023-02-11 19:53 出处:网络
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.

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开发者_如何学Python method? Thank you for helping.


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.)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号