mcast_util.lua 2.06 KB

local _M = {}

local mc = require "skynet.multicast"
local datacenter = require "skynet.datacenter"
local skynet = require "skynet"

local chan_w, chan_g
local chan_ws = {}

function _M.sub_world(w_channel)
	chan_w = mc.new {
		channel = w_channel,
		dispatch = function (channel, source, ...)
			if select("#", ...) == 0 then
				return
			end
			local actionCode, bin = ...
			if SendPacket then
				SendPacket(actionCode, bin)
			end
		end
	}
	chan_w:subscribe()
end

function _M.usub_world()
	if chan_w then
		chan_w:unsubscribe()
		chan_w = nil
	end
end

function _M.sub_worlds(w_channels)
	for _, cell in pairs(w_channels) do
		local chan = mc.new {
			channel = cell,
			dispatch = function (channel, source, ...)
				if select("#", ...) == 0 then
					return
				end
				local actionCode, bin = ...
				if SendPacket then
					SendPacket(actionCode, bin)
				end
			end
		}
		chan:subscribe()
		table.insert(chan_ws, chan)
	end
end

function _M.pub_world(actionCode, bin)
	if not bin then
		return
	end
	if #chan_ws > 0 then
		for _, chan in pairs(chan_ws) do
			chan:publish(actionCode, bin)
		end
		return
	end
	if not bin or not chan_w then return end
	chan_w:publish(actionCode, bin)
end

function _M.sub_union(gid, chan)
	chan_g = mc.new {
		channel = chan,
		dispatch = function (channel, source, ...)
			if select("#", ...) == 0 then
				return
			end
			local actionCode, bin = ...
			if SendPacket then
				SendPacket(actionCode, bin)
			end
		end
	}
	chan_g:subscribe()
end

function _M.usub_union()
	if chan_g then
		chan_g:unsubscribe()
		chan_g = nil
	end
end

function _M.pub_union(actionCode, bin)
	if not bin or not chan_g then return end
	chan_g:publish(actionCode, bin)
end

function _M.pub_person(fromFd, toRoleId, actionCode, bin)
	if 0 == redisproxy:exists(string.format("role:%d", toRoleId)) then
		return SYS_ERROR_CHAT_NOT_EXIST
	end
	-- 若在线,实时发送聊天信息
	local agent = datacenter.get("agent", toRoleId)
	if agent then
		SendPacket(actionCode, bin, agent.fd)
		SendPacket(actionCode, bin, fromFd)
		return
	end
	return SYS_ERROR_CHAT_NOT_ONLINE
end

return _M