[寒江孤叶丶的Cocos2d-x之旅_14]Cocos2d-x 3.2版本以上LUA脚本Socket通讯解决方案——LuaSocket

原创文章,欢迎转载,转载请注明:文章来自[寒江孤叶丶的Cocos2d-x之旅系列]

博客地址:http://blog.csdn.net/qq446569365

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

下边先上一段代码:

    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的性能。

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

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

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

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作为结尾!

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...