从 Quick-Cocos2dx-Community 3.7 开始在 framework 中提供。
Quick-Cocos2dx-Community 中集成了 LuaSocket,为网络游戏提供 Socket 层的连接支撑。
LuaSocket 本身是跨平台的封装,支持 TCP/UDP,但本身使用并不方便。于是 Quick 中集成了一个 SocketTCP的高层封装模块,用来提高易用性。SocketTCP 最早来源于 Quick 论坛中的一份实现,后被 zrong 改进,而 Quick 社区版进一步改进了 IPV6 的网络适应与轮训频率。不过 SocketTCP 的代码质量依然不高,3个调度器直接的切换让人看得眼花缭乱。本着精益求精的精髓,我着手重新设计 TCP 的封装层,并命名为 SimpleTCP。
SimpleTCP 内部按照下面的状态图而设计,理解图就理解了 SimpleTCP 的用法。
状态说明:
self.stcp = SimpleTCP.new()
初始化于 Inited 状态,这个状态无需记录。self.stcp:connect()
到达 Connecting 状态。self.stcp:close()
或 服务器端关闭 socket,触发状态切换到 Closed。self.stcp:connect()
进行重连。self.stcp:connect()
进行重连。事件说明:
导入模块
local SimpleTCP = require("framework.SimpleTCP")
创建对象(类方法)
self.stcp = SimpleTCP.new("127.0.0.1", 1234, handler(self, self.onTCPEvent))
连接服务器(对象方法)
self.stcp:connect()
主动断开连接(对象方法)
self.stcp:close()
发送数据(对象方法)
self.stcp:send(string)
local MainScene = class("MainScene", function()
return display.newScene("MainScene")
end)
local SimpleTCP = require("framework.SimpleTCP")
function MainScene:ctor()
self.stcp = SimpleTCP.new("127.0.0.1", 1234, handler(self, self.onTCPEvent))
self.stcp:connect()
-- Reconnect
local btn = ccui.Button:create():center():addTo(self)
btn:setTitleText("connect")
btn:setTitleFontSize(40)
btn:addTouchEventListener(function(ref, eventType)
if cc.EventCode.ENDED == eventType then
self.stcp:connect()
end
end)
-- close for Reconnet testing
self:performWithDelay(function()
self.stcp:close()
end, 3)
end
function MainScene:onTCPEvent(even, data)
if even == SimpleTCP.EVENT_DATA then
print("==receive data:", data)
elseif even == SimpleTCP.EVENT_CONNECTING then
print("==connecting")
elseif even == SimpleTCP.EVENT_CONNECTED then
print("==connected")
self.stcp:send("Hello server, i'm SimpleTCP")
elseif even == SimpleTCP.EVENT_CLOSED then
print("==closed")
-- you can call self.stcp:connect() again or help user exit game.
elseif even == SimpleTCP.EVENT_FAILED then
print("==failed")
-- you can call self.stcp:connect() again or help user exit game.
end
end
function MainScene:onEnter()
end
function MainScene:onExit()
end
return MainScene