• 已删除用户
skynet实现PingPong
Administrator
发布于 2021-10-08 / 136 阅读 / 0 评论 / 0 点赞

skynet实现PingPong

配置文件 Pconfig 启动主服务 Pmain. Pmain 创建两个 ping 服务 并让 ping1 向 ping2 发送消息. ping2 收到消息会向发送方返回消息.

#examples/Pconfig

include "config.path"

-- preload = "./examples/preload.lua"	-- run preload.lua before every lua service run
-- 必须配置
thread = 8                              -- 启用多少个工作线程
cpath = "./cservice/?.so"               -- 用C编写的服务模块的位置
bootstrap = "snlua bootstrap"           -- (固定)启动的第一个服务

-- bootstrap 配置项
start = "Pmain"                         -- 主服务入口
harbor = 0                              -- (固定)不适应主从节点

-- lua 配置项(暂时固定)
lualoader = "./lualib/loader.lua"
luaservice = "./service/?.lua;".."./test/?.lua;".."./examples/?.lua;".."./test/?/init.lua"
lua_path = "./lualib/?.lua;".."./lualib/?/init.lua"
lua_cpath = "./luaclib/?.so"

-- 后台模式
-- deamon = "./skynet.pid"
-- logger = "./userlog"

#examples/Pmain.lua

local skynet = require "skynet"

skynet.start(function()
    skynet.error("[Pmain] start")
    local ping1 = skynet.newservice("ping")
    local ping2 = skynet.newservice("ping")

    skynet.send(ping1, "lua", "start", ping2)
    skynet.exit()
end)

#examples/ping.lua

local skynet = require "skynet"

local CMD = {}

skynet.start(function()
    skynet.dispatch("lua", function(session, source, cmd, ...)
        local f = assert(CMD[cmd])
        f(source, ...)
    end)
end)

function CMD.start(source, target)
    skynet.send(target, "lua", "ping", 1)
end

function CMD.ping(source, count)
    local id = skynet.self()
    skynet.error("["..id.."] recv ping count="..count)
    skynet.sleep(100)
    skynet.send(source, "lua", "ping", count + 1)
end