(转)0801 - luasocket 在 cocos2d-lua 的应用
pb + luasocket + 收发缓存
原版的 quick 里面带了一个 socketTCP 的 luasocket 封装,但是并没有处理网络粘包和少包等情况。我们在这个基础上扩展一个带收发缓存数据,数据格式是 pb 工具。
local scheduler = require ("cocos.framework.scheduler")
local tcp = require 'cocos.framework.net.SocketTCP'
local headerSize = 2
local NetMgr = class("NetMgr", tcp)
function NetMgr:ctor()
NetMgr.super.ctor(self)
self.recvBuffer = ''
self.process_id = nil
self.send_task_list = {}
self:on(tcp.EVENT_CLOSE, handler(self, self.stop))
self:on(tcp.EVENT_CLOSED, handler(self, self.stop))
self:on(tcp.EVENT_CONNECTED, function ( )
print('connected')
self.process_id = scheduler.scheduleGlobal(function ( dt )
self:processSocketIO()
end, 0.1)
end)
self:on(tcp.EVENT_DATA, function ( data )
self.recvBuffer = self.recvBuffer .. data.data
end)
end
function NetMgr:getInstance()
if not self.instance_ then
self.instance_ = NetMgr:new()
end
return self.instance_
end
function NetMgr:stop()
print('> socket close')
if self.process_id then
scheduler:unscheduleScriptEntry(self.process_id)
end
end
function NetMgr:processSocketIO()
if not self.isConnected then
return
end
self:processInput()
self:processOutput()
end
function NetMgr:processInput()
while true do
local len = string.len(self.recvBuffer)
if len == 0 then
return
end
if len < headerSize then
print('header not full')
return
end
--计算包的长度
local first, sencond = string.byte(self.recvBuffer, 1, 2)
local bodySize = first * 256 + sencond --通过位计算长度
print("收到数据长度 = ",bodySize)
if string.len(self.recvBuffer) < headerSize + bodySize then
print('body not full')
return
end
--解析包
local data = string.sub(self.recvBuffer