cocos2dx使用lua和protobuf

来源:互联网 发布:京东算法工程师待遇 编辑:程序博客网 时间:2024/05/18 00:39

为了使游戏开发更加方便快捷,我继续了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 buildpython 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=nilfunction 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=101local person =test_pb.Person()person.id=111person.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))endlocal function onMessage(strData)print("socket message ...")endlocal function onClose(strData)print("socket close ...")endlocal function onError(strData)print("socket error")endif nil ~= wsProtobuf then        wsProtobuf:registerScriptHandler(onOpen,kWebSocketScriptHandlerOpen)        wsProtobuf:registerScriptHandler(onMessage,kWebSocketScriptHandlerMessage)        wsProtobuf:registerScriptHandler(onClose,kWebSocketScriptHandlerClose)        wsProtobuf:registerScriptHandler(onError,kWebSocketScriptHandlerError)    endend

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

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


原创粉丝点击