您的位置:首页 > 移动开发 > Cocos引擎

cocos2dx使用lua和protobuf

2014-03-05 16:54 621 查看
为了使游戏开发更加方便快捷,我继续了protobuf在lua下的尝试。

socket使用的是cocos2dx集成的websocket。

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

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

[plain] view plaincopy





python setup.py build

python setup.py install


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


[plain] view plaincopy





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

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

[plain] view plaincopy





<你的路径>/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文件,添加如下代码:

[cpp] view plaincopy





extern "C"{

#include <lua.h>

#include <lualib.h>

#include <lauxlib.h>

int luaopen_pb (lua_State *L);

}

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

[cpp] view plaincopy





luaopen_pb(tolua_s);

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

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

[javascript] view plaincopy





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()函数即可。

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: