sniper00 / moon

A lightweight game server framework implemented with Actor Model
MIT License
721 stars 158 forks source link

moon.new_service是怎么返回服务id的? #153

Closed axiullo closed 2 years ago

axiullo commented 2 years ago

moon.new_service这个api是怎么获得服务id并返回的? 看了好久也没有捋清楚. math.tointeger(co_yield()) 不是应该挂起当前协程么?

我写了个例子, 我理解的是moon.new_service 执行完都需要再次执行coroutine.resume才能把for循环跑完. 因为new_service最后yield的了? 但是实际是for循环是一次都执行完了,并没有中途挂起, 而且返回了服务id. 一直也没有看懂这服务id怎么来的. 求帮忙讲解一下.

moon.async(function()
    local conf = {
        base_name = "gate",
        file = "service_gate.lua",
        host = "0.0.0.0",
        base_port = 20520,
        num = 5,
        unique = true, -- 通过name做唯一区分,name不能相同
    }

    for i = 1, conf.num do
        conf.port = conf.base_port + i - 1
        conf.name = conf.base_name .. i
        local r = moon.new_service("lua", conf)
    end
end)
sniper00 commented 2 years ago

moon.new_service 是会挂起的

function moon.new_service(stype, config)
    local sessionid = make_response()
    _newservice(stype, sessionid, config)
    return math.tointeger(co_yield())
end

make_response() 会关联当前协程一个 sessionid, 把创建服务请求发送个底层 void worker::new_service(std::unique_ptr<service_conf> conf), 最后把结果 服务ID通过server::response 返回给lua层,消息类型是 PTYPE_TEXT. moon.lua_default_dispatch 会根据sessionid找到上面关联的协程调用 coresume(co, p.unpack(sz, len))

axiullo commented 2 years ago

明白了. 谢谢. 各种绕来绕去, 有点晕.

sniper00 commented 2 years ago

明白了. 谢谢. 各种绕来绕去, 有点晕.

其实你可以理解为有些API是向cpp层发起call调用,这些API的实现步骤基本都是按我上面说的。这种API的数量极少:

moon.new_service
moon.remove_service
moon.sleep