`
aigo
  • 浏览: 2537512 次
  • 性别: Icon_minigender_1
  • 来自: 宜昌
社区版块
存档分类
最新评论

ios开发中使用cocos2dx、lua和protobuf

阅读更多

 原文:http://www.cnblogs.com/hanframe/p/3582832.html

 

为了使游戏开发更加方便快捷,我继续了protobuf在lua下的尝试。

socket使用的是cocos2dx集成的websocket。

 

先说下环境:cocos2d-x-2.2.1 + protobuf 2.5.0 + protoc-gen-lua + Python 2.7.5

 

1.在protobuf目录下依次执行如下命令

python setup.py build  
python setup.py install  

 

 

2.在protoc-gen-lua目录下的plugin目录中新建protoc-gen-lua.bat文件,并将如下内容粘贴到里面

@python <你的目录>\protoc-gen-lua\plugin\protoc-gen-lua  

 

 

3.生成protobuf对应的lua文件,执行如下命令:

<你的路径>/protoc.exe --lua_out=./ --plugin=protoc-gen-lua="<你的路径>\protoc-gen-lua\plugin\protoc-gen-lua.bat" test.proto  

 

执行完后就会生成test_pb.lua文件。

 

4.使用cocos2dx的create_project.py创建lua工程;

 

5.将protoc-gen-lua/protobuf目录下的pb.c文件复制到lua工程的Classes目录下,并加入到C++工程中;

 

6.将protoc-gen-lua/protobuf目录下的所有lua文件复制到lua工程的Resources目录下;

 

7.编辑AppDelegate.cpp文件,添加如下代码:

extern "C"{    
#include <lua.h>    
#include <lualib.h>    
#include <lauxlib.h>    
    int luaopen_pb (lua_State *L);    
}  

 

 

8.在AppDelegate::applicationDidFinishLaunching()方法中加入初始化方法:

luaopen_pb(tolua_s);  

 

 

9.此时对lua工程进行编译,如果出错,请检查并修正;编译通过,并且可以正常运行后继续下面的步骤;

 

10.cocos2dx默认产生的lua工程包含2个文件hello.lua与hello2.lua,打开hello2.lua,将如下内容添加到文件末尾(因为我使用的是websocket,各位可根据自己的实际情况进行修改):

local wsProtobuf=nil  
function testProtobuf()  
    wsProtobuf = WebSocket:create("ws://localhost:8080/web")  
    local function onOpen(strData)  
        print("socket open ...")  
        require "test_pb"  
        local msg=test_pb.Message()  
        msg.id=101        
        local person =test_pb.Person()  
        person.id=111  
        person.name="user1"  
        person.email="a1@a.a"  
        msg.data=person:SerializeToString()  
        local pb_data = msg:SerializeToString()  
        local t={string.byte(pb_data,1,-1)}  
        wsProtobuf:sendBinaryMsg(t,table.getn(t))  
    end  
    local function onMessage(strData)  
        print("socket message ...")  
    end  
    local function onClose(strData)  
        print("socket close ...")  
    end  
    local function onError(strData)  
        print("socket error")  
    end  
      
    if nil ~= wsProtobuf then  
        wsProtobuf:registerScriptHandler(onOpen,kWebSocketScriptHandlerOpen)  
        wsProtobuf:registerScriptHandler(onMessage,kWebSocketScriptHandlerMessage)  
        wsProtobuf:registerScriptHandler(onClose,kWebSocketScriptHandlerClose)  
        wsProtobuf:registerScriptHandler(onError,kWebSocketScriptHandlerError)  
    end   
end  

 

 

11.然后在hello.lua中调用testProtobuf()函数即可。

 

测试运行,你可以在服务器端查看收到的消息。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics