在lua中,如果是使用http來請求的是字節流的數據
那麼在cocos2dx v3.3中 需要使用xmlhttprequest這個類
在處理獲取的字節流數據時,首先需要轉化字節流爲字符串,轉換的方法是:string.char
local response = xhr.response -- 獲得返回數據
for i = 1,size do
byteData = byteData..string.char(response[i])
end
這個辦法的特點是一個字符一個字符的處理。還有一個批量處理的方法。那就是使用unpack方法。
local response = xhr.response -- 獲得返回數據
byteData = byteData..string.char( unpack(response))
這種批量處理的方式的好處是,能夠批量處理,速度較快。
但是這樣處理還有一個缺點,那就是看網上說一次最大隻能處理10k的數據,也就是長度爲10000個字節的數據
而且在我的遊戲這種長度是不夠的,我需要處理的是40000左右字節的數據
苦思冥想之後,想到的辦法是:首先把response的數據分塊,分塊之後,對每一塊進行轉化成數據,然後在合成一個完整的字符串。
在這個過程中,一定要注意數據的完整性。
下面這段代碼是分成10塊進行分別處理的
local part = 10
local partData = ""
local startIndex = 1
local partIndex,endIndex1 = math.modf(size/part)
local endIndex = partIndex
print(" endIndex is "..endIndex)
print(" endIndex1 is "..endIndex1)
for i=1,part do
local partUnPack = string.char(unpack(response,startIndex,endIndex))
startIndex = startIndex + partIndex
endIndex = endIndex + partIndex
partData = partData..partUnPack
print(" startIndex is "..startIndex)
print(" 解碼 i is "..i.." time is "..os.time())
end
local rest = size % part --求餘數
-- print(" rest is "..rest)
-- print("startIndex is "..startIndex)
local restData = ""
for i=1,rest do
restData = restData..string.char(response[startIndex+i-1])
end
-- print("the datalen is "..(startIndex+rest).." the size is "..size)
-- print("restData "..restData)
partData = partData..restData
partData的數據就是最後的結果。
性能分析:
在windows上面,40000字節的數據需要5秒的時間,而使用unpack之後,就幾乎不需要時間。順利通過了。