cocos2d-x 3.x封装socket方法

在Coco2d-x3.2版本中,对LuaSocket进行了集成,我们可以直接在程序中调用luaSocket进行方便的TCP/UDP/FTP/HTTP等等通讯,非常方便。

下边先上一段代码:

 

01. local socket = require("socket")
02. local host = "115.28.*.*"
03. local port = 8890
04. local c = socket.tcp()
05. --c:settimeout(5)
06. local n,<span style="font-family: Arial, Helvetica, sans-serif;">e</span><span style="font-family: Arial, Helvetica, sans-serif;"> = c:connect(host, port)</span>
07. print("connect return:",n,e)--通过判断n可以判断连接是否成功,n是1表示成功 n是nil表示不成功
08. c:send("Hello")
09. while true  do
10. local response, receive_status=c:receive()
11. --print("receive return:",response or "nil" ,receive_status or "nil")
12. if receive_status ~= "closed" then
13. if response then
14. print("receive:"..response)
15. end
16. else
17. break
18. end
19. end
20. end
这段代码实现了TCP的链接,并像服务器发送了一段“Hello”,然后便阻塞进程等待服务器消息了。

 

说到阻塞,就不得不提到多进程,然后在LUA中,使用多线程会极大程度降低LUA的性能。

这里 LuaSocket提供了一个不错的解决方案:c:settimeout(0)

经过这样的设置,程序便不会发生阻塞,然后在schedule中循环调用即可。

附上一个目前我程序中的临时解决方案:

 

01. function socketInit()
02. local socket = require("socket")
03. local host = "115.28.*.*"
04. local port = 8890
05. G_SOCKETTCP = socket.tcp()
06. local n,e = G_SOCKETTCP:connect(host, port)
07. print("connect return:",n,e)
08. G_SOCKETTCP:settimeout(0)
09. end
10. function socketClose()
11. G_SOCKETTCP:close()
12. end
13. function socketSend(sendStr)
14. G_SOCKETTCP:send(sendStr)
15. end
16. function socketReceive()
17. local response, receive_status=G_SOCKETTCP:receive()
18. --print("receive return:",response or "nil" ,receive_status or "nil")
19. if receive_status ~= "closed" then
20. if response then
21. print("Receive Message:"..response)
22. --对返回的内容进行解析即可
23. end
24. else
25. print("Service Closed!")
26. end
27. end
然后在程序中进行调用即可
01. socketInit()
02. local timePassed = 0
03. local function myHandler(dt)
04. timePassed= timePassed + dt
05. if timePassed > 0.1 then
06. socketReceive()
07. timePassed= 0
08. end
09. end
10. self:scheduleUpdateWithPriorityLua(myHandler,1)
11. --print(self.roomType)
12. local jsonStr=getRoomInformationJson(self.roomType)
13. print(jsonStr)
14. socketSend(jsonStr)

猜你喜欢

转载自blog.csdn.net/sun___shine/article/details/52089649