LuaSocket 服务器如何同时处理多个请求?
问题是我的 Lua 服务器无法同时接受多个请求。 我尝试让每个客户端消息在其协程中处理,但这似乎失败了。
while true do
local client = server:accept()
coroutine.resume(coroutine.create( function()
GiveMessage( client )
end ) )
end
这段代码似乎实际上并没有同时接受多个客户端消息。这个方法有什么问题吗?谢谢你的帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将无法仅使用协程创建真正的同时处理 - 协程用于协作多任务处理。同时只有一个协程被执行。
您编写的代码与直接在循环中调用
GiveMessage()
没有什么不同。您需要编写一个协程调度程序,并找到一个合理的理由从GiveMessage()
中屈服,以使该方法发挥作用。根据任务的具体情况,至少有三种解决方案:
生成服务器的多个分支,在每个分支中处理协程中的操作。使用 Copas 或 lua-ev 或使用自制的调度程序,这没有问题。我推荐这种方式。
使用 Lua 状态而不是协程,保留状态池、工作操作系统线程池和任务队列。使用空闲工作线程在空闲 Lua 状态下执行每个任务。需要一些低级编码,而且比较混乱。
寻找现有的更专业的解决方案 - 有几个,但为了提供建议,我需要更好地了解您正在编写的服务器类型。
无论您选择什么,请避免同时从多个线程使用单个 Lua 状态。 (只要编写适量的代码,这是可能的,但这是一个坏主意。)
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 fromGiveMessage()
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 协程不能很好地与开箱即用的 luaSocket 配合使用。但是您可以使用Copas。
AFAIK coroutines don't play nice with luaSocket out-of-the-box. But there is Copas you can use.