LuaSocket服务器如何同时处理多个请求? [英] How can a LuaSocket server handle several requests simultaneously?

查看:170
本文介绍了LuaSocket服务器如何同时处理多个请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是我的Lua服务器无法同时接受多个请求. 我试图使每个客户端消息都在协程中进行处理,但这似乎失败了.

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.

推荐答案

您将无法仅使用协程创建真正的同时处理—协程用于合作多任务处理.同一时间只能执行一个协程.

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.

您编写的代码与直接在循环中调用GiveMessage()没什么不同.您需要编写一个协程分派器,并找到从GiveMessage()屈服的明智原因,这种工作方式才能实现.

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:

  • 生成服务器的多个fork,在每个fork中以协程处理操作.使用 Copas 或使用

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

使用Lua状态而不是协程,保留状态池,辅助OS线程池和任务队列.使用空闲的工作线程在空闲的Lua状态下执行每个任务.需要一些底层编码并且更混乱.

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.

无论选择什么,都应避免同时使用多个线程中的单个Lua状态. (有可能,使用正确的编码量,但不是个好主意.)

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

这篇关于LuaSocket服务器如何同时处理多个请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆