skynet实现Echo 基础上实现多人聊天

#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"
local socket = require "skynet.socket"

local clients = {}

skynet.start(function()
    local listenfd = socket.listen("0.0.0.0", 8888)
    socket.start(listenfd, connect)
end)

function connect(fd, addr)
    -- 启动连接
    print(fd.." connected addr:"..addr)
    socket.start(fd)
    clients[fd] = {}
    -- 消息处理
    while true do
        local readdata = socket.read(fd)
        -- 正常接受
        if readdata ~= nil then
            print(fd.." recv "..readdata)
            for i, _ in pairs(clients) do -- 广播
                socket.write(i, readdata)
            end
        -- 断开连接
        else
            print(fd.."close ")
            socket.close(fd)
            clients[fd] = nil
        end
    end
end

Q.E.D.