Skynet> gate.lua

2 篇文章 0 订阅

最近在学习Skynet,做了一点注解,方便以后学习.

local skynet = require "skynet"
local gateserver = require "snax.gateserver"
local netpack = require "skynet.netpack"

local watchdog
local connection = {}    -- fd -> connection : { fd , client, agent , ip, mode }
local forwarding = {}    -- agent -> connection

skynet. register_protocol {
    name = "client",
    id = skynet. PTYPE_CLIENT,
}

local handler = {}

function handler.open( source, conf)
    watchdog = conf. watchdog or source
end

function handler.message( fd, msg, sz)
     -- recv a package, forward it
     local c = connection[fd]
     local agent = c. agent
     if agent then
        skynet. redirect(agent, c. client, "client", 1, msg, sz)
     else
        skynet. send(watchdog, "lua", "socket", "data", fd, netpack. tostring(msg, sz));
     end

     -- 群发消息
     for key,value in pairs(connection) do
        skynet. send(watchdog, "lua", "socket", "data", value. fd, netpack. tostring( "这是群发消息内容", sz));
     end
end

function handler.connect( fd, addr)
     local c = {
        fd = fd,
        ip = addr,
    }
     -- 存储连接客户端数据
    connection[fd] = c;
    skynet. send(watchdog, "lua", "socket", "open", fd, addr)
end

-- 注销client
local function unforward( c)
     if c. agent then
        forwarding[c. agent] = nil
        c. agent = nil
        c. client = nil
     end
end

-- 关闭client
local function close_fd( fd)
     local c = connection[fd]
     if c then
         unforward(c)
        connection[fd] = nil
     end
end

function handler.disconnect( fd)
     close_fd(fd)
    skynet. send(watchdog, "lua", "socket", "close", fd)
end

function handler.error( fd, msg)
     close_fd(fd)
    skynet. send(watchdog, "lua", "socket", "error", fd, msg)
end

function handler.warning( fd, size)
    skynet. send(watchdog, "lua", "socket", "warning", fd, size)
end

local CMD = {}

function CMD.forward( source, fd, client, address)
     local c = assert(connection[fd])
     unforward(c)
    c. client = client or 0
    c. agent = address or source
    forwarding[c. agent] = c
    gateserver. openclient(fd)
end

function CMD.accept( source, fd)
     local c = assert(connection[fd])
     unforward(c)
    gateserver. openclient(fd)
end

function CMD.kick( source, fd)
    gateserver. closeclient(fd)
end

function handler.command( cmd, source, ...)
     local f = assert(CMD[cmd])
     return f(source, ...)
end

gateserver. start(handler)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值