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

skynet实现Echo

实现一个skynet程序, 回显客户端发送的文字

#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"

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

    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)
    -- 消息处理
    while true do
        local readdata = socket.read(fd)
        -- 正常接受
        if readdata ~= nil then
            print(fd.." recv "..readdata)
            socket.write(fd, readdata)
        -- 断开连接
        else
            print(fd.."close ")
            socket.close(fd)
        end
    end
end