cocos2dx 网络连接


XMLHttpRequest

----------------------------------------------
-- 数据转换,将请求数据 由table转化为string
function dataParse(data)
	
	if type(data) ~= "table" then
		return nil
	end
	local tmp = {}
	for key,value in pairs(data) do
		table.insert(tmp,key .. "=" .. value)
	end
	local newData = ""
	for i = 1,#tmp do
		newData = newData .. tostring(tmp[i])
		if i < #tmp then
			newData = newData .. "&"
		end
	end
	-- cclog("data:" .. newData)
	return newData
end

---------------------------------
-- POST 型,发送数据
function sendInfoToSync()
	
	local url = "www.baidu.com" 				-- 网址
	local xhr = cc.XMLHttpRequest:new()
	xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
	xhr.timeout = 30			-- 判断连接超时时间,秒

	-- 响应函数
	local onReadyFunc = function()
		if xhr.status ~= -1 then		-- 连接成功
			local result = xhr.response 			-- string
			local cjson = require("cjson")
			local info = cjson.decode(result)		-- json 解析成table
		else  		-- 连接失败
		end
	end
	xhr:registerScriptHandler(onReadyFunc)
	xhr:open("POST",url)
	local data = {}
	data.account = 1
	local newData = dataParse(data)
	xhr:send(newData)
end

--------------------------------------
-- GET型,获取数据
function loadInfoFromSync()
	
	local url = "www.baidu.com"
	local xhr = cc.XMLHttpRequest:new()
	xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON
	xhr.timeout = 30
	local onReadyFunc = function()
		if xhr.status ~= -1 then		-- 连接成功
			local result = xhr.response 			-- string
			local cjson = require("cjson")
			local info = cjson.decode(result)		-- json 解析成table
		else  		-- 连接失败
		end
	end
	xhr:registerScriptHandler(onReadyFunc)
	local data = {}
	data.account = 1
	local newData = url .. "?" .. dataParse(data)
	xhr:open("GET",newData)
	xhr:send()
end

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...