How can a LuaSocket server handle several requests simultaneously?

我们两清 提交于 2019-12-08 04:43:02

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/5047951/how-can-a-luasocket-server-handle-several-requests-simultaneously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!