LuaSocket 服务器如何同时处理多个请求?

发布于 2024-10-17 21:22:00 字数 261 浏览 4 评论 0原文

问题是我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌辣 2024-10-24 21:22:00

您将无法仅使用协程创建真正的同时处理 - 协程用于协作多任务处理。同时只有一个协程被执行。

您编写的代码与直接在循环中调用 GiveMessage() 没有什么不同。您需要编写一个协程调度程序,并找到一个合理的理由从 GiveMessage() 中屈服,以使该方法发挥作用。

根据任务的具体情况,至少有三种解决方案:

  • 生成服务器的多个分支,在每个分支中处理协程中的操作。使用 Copaslua-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 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.)

So要识趣 2024-10-24 21:22:00

AFAIK 协程不能很好地与开箱即用的 luaSocket 配合使用。但是您可以使用Copas

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文