login.lua 2.12 KB
local MsgPack = MsgPack
local skynet = require "skynet"

local _M = class("login", require("unitTest.unitTest"))

function _M:start()
	requestServer(actionCodes.Role_queryLoginRpc, MsgPack.pack({uid = self.client.uid}), handler(self, self.onQueryLogin))
end

function _M:onQueryLogin(data)
	local msg = MsgPack.unpack(data)

	if msg.ret == "RET_NOT_EXIST" then
		requestServer(actionCodes.Role_createRpc, MsgPack.pack({ uid = self.client.uid }),  function(data2)
			local msg2 = MsgPack.unpack(data2)
			self:sendLogin(msg2.roleName)
		end)
	elseif msg.ret == "RET_HAS_EXISTED" then
		self:sendLogin(msg.name)
	elseif msg.ret == "INNER_ERROR" then
		-- 过几秒中尝试登录
		-- local time = math.random(5)*100
		-- skynet.timeout(time, function ()
		-- 	rpcServer(actionCodes.Role_queryLoginRpc, MsgPack.pack({uid = self.client.uid}))
		-- end)
		print("INNER_ERROR")
	end
end


function _M:sendLogin(name)
	self.client.name = name

	local totalWave = 0
	local roleData = {}
	local waveTag = {}

	requestServer(actionCodes.Role_loginRpc, MsgPack.pack({name = self.client.name, codeVersion = 1}), function(data)
		local msg = MsgPack.unpack(data)
		if msg.wave then
			totalWave = msg.wave
			for key, value in pairs(msg) do
				roleData[key] = value
			end
			waveTag[1] = true
		end

		if msg.runeWave then
			if not roleData.runeBag then
				roleData.runeBag = {}
			end
			for _, rune in pairs(msg.runeBag) do
				table.insert(roleData.runeBag, rune)
			end
			waveTag[msg.runeWave] = true
		end

		if msg.heroWave then
			if not roleData.heros then
				roleData.heros = {}
			end
			for _, hero in pairs(msg.heros) do
				table.insert(roleData.heros, hero)
			end
			waveTag[msg.heroWave] = true
		end

		if msg.chatWave then
			waveTag[msg.chatWave] = true
		end

		-- 检查是否全部接收完
		if totalWave > 0 then
			local finish = true
			for _wave = 1, totalWave do
				if not waveTag[_wave] then
					finish = false
					break
				end
			end
			if finish then
				self.client.role = roleData
				removeListener(actionCodes.Role_loginRpc)
				pcall(skynet.call, skynet.self(), "lua", "task")  -- 开始任务
			end
		end
	end, true)
end

return _M