原创文章,欢迎转载,转载请注明:文章来自[寒江孤叶丶的Cocos2d-x之旅系列]@H_502_1@
博客地址:http://blog.csdn.net/qq446569365@H_502_1@
在Coco2d-x3.2版本中,对LuaSocket进行了集成,我们可以直接在程序中调用luaSocket进行方便的TCP/UDP/FTP/HTTP等等通讯,非常方便。@H_502_1@
@H_502_1@
local socket = require("socket") local host = "115.28.*.*" local port = 8890 local c = socket.tcp() --c:settimeout(5) local n,<span style="font-family: Arial,Helvetica,sans-serif;">e</span><span style="font-family: Arial,sans-serif;"> = c:connect(host,port)</span> print("connect return:",n,e)--通过判断n可以判断连接是否成功,n是1表示成功 n是nil表示不成功 c:send("Hello") while true do local response,receive_status=c:receive() --print("receive return:",response or "nil",receive_status or "nil") if receive_status ~= "closed" then if response then print("receive:"..response) end else break end end end这段代码实现了TCP的链接,并像服务器发送了一段“Hello”,然后便阻塞进程等待服务器消息了。
说到阻塞,就不得不提到多进程,然后在LUA中,使用多线程会极大程度降低LUA的性能。@H_502_1@
这里 LuaSocket提供了一个不错的解决方案:c:settimeout(0)@H_502_1@
经过这样的设置,程序便不会发生阻塞,然后在schedule中循环调用即可。@H_502_1@
@H_502_1@
function socketInit() local socket = require("socket") local host = "115.28.*.*" local port = 8890 G_SOCKETTCP = socket.tcp() local n,e = G_SOCKETTCP:connect(host,port) print("connect return:",e) G_SOCKETTCP:settimeout(0) end function socketClose() G_SOCKETTCP:close() end function socketSend(sendStr) G_SOCKETTCP:send(sendStr) end function socketReceive() local response,receive_status=G_SOCKETTCP:receive() --print("receive return:",receive_status or "nil") if receive_status ~= "closed" then if response then print("Receive Message:"..response) --对返回的内容进行解析即可 end else print("Service Closed!") end end然后在程序中进行调用即可
socketInit() local timePassed = 0 local function myHandler(dt) timePassed= timePassed + dt if timePassed > 0.1 then socketReceive() timePassed= 0 end end self:scheduleUpdateWithPriorityLua(myHandler,1) --print(self.roomType) local jsonStr=getRoomInformationJson(self.roomType) print(jsonStr) socketSend(jsonStr)
在Lua程序设计第二版中,提到了通过C语言函数来实现LUA多线程的功能,我会在下一篇博客中详细介绍。
特别提醒:LuaSocket在receive的时候,是把\n当成结尾,如果没有\n,会出现timeout的错误,所以服务器在发送消息的时候,一定要记得在消息的最后加一个\n作为结尾!@H_502_1@ 原文链接:https://www.f2er.com/cocos2dx/347083.html