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

来源:互联网 发布:淘宝热门店铺秒杀技巧 编辑:程序博客网 时间:2024/06/05 19:53

原创文章,欢迎转载,转载请注明:文章来自[寒江孤叶丶的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, Helvetica, 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:",n,e)    G_SOCKETTCP:settimeout(0)endfunction socketClose()    G_SOCKETTCP:close()endfunction socketSend(sendStr)    G_SOCKETTCP:send(sendStr)endfunction socketReceive()    local response, receive_status=G_SOCKETTCP:receive()        --print("receive return:",response or "nil" ,receive_status or "nil")        if receive_status ~= "closed" then            if response then                print("Receive Message:"..response)                --对返回的内容进行解析即可            end        else            print("Service Closed!")        endend
然后在程序中进行调用即可
    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作为结尾!


1 0
原创粉丝点击