使用节点集群建立分布式PingPong

#examples/Pconfig.c1

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"

-- 集群
node = "node1"

#examples/Pconfig.c2

...同Pconfig.c1...

-- 集群
node = "node2"

#examples/Pmain.lua

local skynet = require "skynet"
local cluster = require "skynet.cluster"
require "skynet.manager"

skynet.start(function()
    cluster.reload({
        node1 = "127.0.0.1:9101",
        node2 = "127.0.0.1:9102"
    })
    local mynode = skynet.getenv("node")

    if mynode == "node1" then
        cluster.open("node1")
        local ping1 = skynet.newservice("ping")
        local ping2 = skynet.newservice("ping")

        skynet.send(ping1, "lua", "start", "node2", "pong", 1)
        skynet.send(ping2, "lua", "start", "node2", "pong", 101)

    elseif mynode == "node2" then
        cluster.open("node2")
        local ping3 = skynet.newservice("ping")
        skynet.name("pong", ping3)
    end
end)

#examples/ping.lua

local skynet = require "skynet"
local cluster = require "skynet.cluster"
local mynode = skynet.getenv("node")

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_node, target, count)
    cluster.send(target_node, target, "ping", mynode, skynet.self(), count)
end
 
function CMD.ping(source, source_node, source_srv, count)
    local id = skynet.self()
    skynet.error("["..id.."] recv ping count="..count)
    skynet.sleep(100)
    cluster.send(source_node, source_srv, "ping", mynode, skynet.self(), count + 1)
end

Q.E.D.