cocos2d-x lua 中使用protobuf并对http进行处理
本文介绍 cocos2d-x lua 中使用http 和 基于cocos2d-x 对lua http的封装(部分ok)
本博客链接
http://blog.csdn.net/vpingchangxin/article/details/24458051
protobuf Google的一个很好用的传输数据的封装 说实话Google的东西确实比较好用 所以我们前后端数据交换就用他了 不过Google没有对lua进行支持 还好社区有开源的大侠们贡献 找了所有关于lua protobuf 我只找到 云风的 pbc 修改相关cocos2d-x中的类可以正常使用。protoc-gen-lua 我在使用的时候 总是报截断数据 在修改后cocs2d-x中的类之后没有对protoc-gen-lua 进行测试是否是这个问题导致
1)集成 云风 云大侠的(博客)lua-pbc 标准c写的protobuf 具体看pbc的帮助很轻松集成
2) 生成pb文件(我自己写了个mac中批处理生成所有.proto文件为.pb文件)把pb 和proto文件都加入到项目资源中
- #!/bin/sh
- #pb = "pb"
- for i in *.proto
- do
- #echo $i
- #echo ${i%.*}".pb"
- #echo ${i%.*}
- #pbn = $i | cut -d.
- pbname=${i%.*}".pb"
- #echo $pbn
- #echo $pbname
- protoc --descriptor_set_out $pbname $i
- done
- echo "finish"
也可以用命令行手动生成
- protoc --descriptor_set_out aaa.pb aaa.proto
- local protobuf = require "protobuf"
- local buffer = CCFileUtils:sharedFileUtils():getFileData("entity/p_result.pb","r",0)
- -- print(buffer)
- protobuf.register(buffer)
修改CCFileUtils.cp getFileData(const char* pszFileName, const char* pszMode,unsignedlong * pSize)方法(在最后添加\0,保证字节不多余)如下代码
- unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize)
- {
- unsigned char * pBuffer = NULL;
- CCAssert(pszFileName != NULL && pSize != NULL && pszMode != NULL, "Invalid parameters.");
- *pSize = 0;
- do
- {
- // read the file from hardware
- std::string fullPath = fullPathForFilename(pszFileName);
- FILE *fp = fopen(fullPath.c_str(), pszMode);
- CC_BREAK_IF(!fp);
- fseek(fp,0,SEEK_END);
- *pSize = ftell(fp);
- fseek(fp,0,SEEK_SET);
- pBuffer = new unsigned char[*pSize];
- *pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp);
- fclose(fp);
- } while (0);
- if (*pSize >0 && pBuffer[*pSize] != '\0')
- pBuffer[*pSize] = '\0';
- if (! pBuffer)
- {
- std::string msg = "Get data from file(";
- msg.append(pszFileName).append(") failed!");
- CCLOG("%s", msg.c_str());
- }
- return pBuffer;
- }
5)经过上一步骤lua层基本搞定可以创建本地的数据并encode成传输数据到服务器端了 如下代码
- local major = {
- majorId = "795f94a9-3466-41b4-bf16-043ba8081fab"
- }
- local buffer = protobuf.encode("com.sj.web.proto.Major", major)
- local t = protobuf.decode("com.sj.web.proto.Result", request:getResponseString())--tolua.cast(event.dataCString))--tolua.cast(event.dataCString,"CCString"):getCString())
- cclog(t)
- print(t.major.gender)
- print(t.major.majorId)
- print(t.user.username)
(1)我先前用的是quick-cocos2d-x-lua中封装的CCHTTPRequest的这个进行服务器端交互 不过不如愿 因为服务器端过来的数据中是protobuf进行处理过的数据 在进行调试跟踪后发现过来的数据中不定什么地方都有\0结束符 这个导致直接在lua中调研CCHTTPRequest中的获取string 方法数据被截断不能正常解析 我在CCHTTPRequest::getResponseString进行处理过来的数据处理掉\0 也不行
(2)由于项目中要用的短连接socket我先前已经集成好luasocket,其实这个开源的socket很好用 也有对http的支持果断用这个测试下服务器端回来的数据 让我小小喜悦了一下 丢到protobuf.decode中进行解析正是我要的数据 不过有个不好的地方 luasocket对socket有设置一个超时时间 就可以不阻塞线程 但是htpp方式我找遍了网站上的资料也没找到非阻塞式的 不过这个没关系比较可以正常跑protobuf了 集成一个线程框架就ok了呀 可以用协同线程 或者是lua llthreads 自己选择吧如果要用 luasocket的http 先附上luasocket的http代码
- local http = require 'socket.http'
- local ltn12 = require 'ltn12'
- response_body = ""
- request_body = ""
- function http.post(u)
- local t = {}
- local r, c, h = http.request{
- url = u,
- method = "POST",
- headers = {
- ["Content-Type"] = "application/x-protobuf",
- ["Content-Length"] = #request_body,
- },
- source = ltn12.source.string(request_body),
- sink = ltn12.sink.table(t)}
- return r, c, h, t
- end
- -- url = "http://www.baidu.com"
- r,c,h,body=http.post(HTTP_URL)
- print(c)
- if c~= 200 then
- return
- end
- local protobuf = require "protobuf"
- local buffer = CCFileUtils:sharedFileUtils():getFileData("entity/p_result_test.pb","r",0)
- -- print(buffer)
- protobuf.register(buffer)
- local t = protobuf.decode("com.sj.web.proto.Result", body[1])
- cclog(t)
(3)不过我没有用上面中提到的luasocket http 个人感觉还是直接用coco2d-x中的CCHttpClient比较好用也不用处理线程的东西 因为我通过这个测试过c++层中protobuf进行解析是完全没问题的所以我就模仿(1)中提到的CCHTTPRequest对cocos2d :: extension :: CCHttpClient封装使用不过有点不顺利数据传到lua层还是不正常,
- std::vector<char> *data = response->getResponseData();
- std::stringstream mystream;
- for(int i=0;i<data->size();i++){
- //if ((*data)[i] != '\0') {
- mystream << (*data)[i];
- //}else{
- // mystream << '\b';
- //}
- }
- mResponseData = mystream.str();
- std::cout << mystream.str() << std::endl;
- CCLog("ddd:%s",mystream.str().c_str());
- CCString * cstr = CCString::create(temp);
- // com::sj::web::proto::Result *r = new com::sj::web::proto::Result::Result();
- // r->ParseFromString(temp.c_str());
- // CCLog("ParseFromString:::::::::%d %s",r->resultcode(),r->release_major()->majorcode().c_str());
- CCLuaValueDict dict;
- dict["request"] = CCLuaValue::ccobjectValue(this, "HTTPRequest");
- dict["data"] = CCLuaValue::stringValue(mystream.str()); // 传值回到lua层
- dict["dataCString"] = CCLuaValue::ccobjectValue(cstr, "CCString");
- dict["dddd"] = CCLuaValue::stringValue("dssddsdsds");
- LUA_FUNCTION listener = (LUA_FUNCTION)response->getHttpRequest()->getUserData();
- CCLuaStack *stack = CCLuaEngine::defaultEngine()->getLuaStack();
- stack->clean();
- stack->pushCCLuaValueDict(dict);
做好上一步进行修改cocos2d-x CCLuaStack.cpp 方法pushCCLuaValue(....) 中 代码293行代码,修改如下(这样做可以直接使用 lua_pushlstring(m_state, stringValue, length) 把所有数据压到lua上层)
- return pushString(value.stringValue().c_str(), value.stringValue().length());
完整方法代码为:
- void CCLuaStack::pushCCLuaValue(const CCLuaValue& value)
- {
- const CCLuaValueType type = value.getType();
- if (type == CCLuaValueTypeInt)
- {
- return pushInt(value.intValue());
- }
- else if (type == CCLuaValueTypeFloat)
- {
- return pushFloat(value.floatValue());
- }
- else if (type == CCLuaValueTypeBoolean)
- {
- return pushBoolean(value.booleanValue());
- }
- else if (type == CCLuaValueTypeString)
- {
- return pushString(value.stringValue().c_str(), value.stringValue().length()); //pushString(value.stringValue().c_str());
- }
- else if (type == CCLuaValueTypeDict)
- {
- pushCCLuaValueDict(value.dictValue());
- }
- else if (type == CCLuaValueTypeArray)
- {
- pushCCLuaValueArray(value.arrayValue());
- }
- else if (type == CCLuaValueTypeCCObject)
- {
- pushCCObject(value.ccobjectValue(), value.getCCObjectTypename().c_str());
- }
- }
好了就介绍到这里吧希望对cocos2d-x lua 开发的同行们有所帮助 如果有什么好的protobuf对cocos2d-x lua 的支持 或者是更方便的集成 也请贡献给我一份哟 谢谢
本人用风云的pbc 心得 总的来说还算可以
1)浮点类型:java—>lua 没问题;lua—>java 没通过。我们后端用的java 估计是lua对number浮点数类型进行decode的 有整形进行传递的时候导致没有进行对浮点类型转换(或者java对类型比较严格导致解码的时候对高地位转换失败所致) 由于开发效率前后端改成string进行传递(测试过protoc-gen-lua 也有这个问题)如有朋友能使用lua—>java进行浮点类型通信OK 迫切滴希望您共享我一份解决方案
2)枚举类型 proto文件中序号从1开始计数 否则pbc pb文件加载失败
3)上面提到的加载pb文件的时候ios win 也可以根据 CCFileUtils获取pb文件路径后用 lua io进行注册,测试android(我还是用上面提到的方法进行读文件)用这种方式没成功 应该是路径和权限问题导致(已经验证过是android中读取文件路径问题,我的方式是把proto写到本地后lua用io进行读取ok)读不到文件
- --其他平台
- local filePath = CCFileUtils:sharedFileUtils():fullPathForFilename("entity/p_result.pb")
- local addr = io.open(filePath,"rb")
- protobuffer = addr:read "*a"
- addr:close()
- protobuf.register(protobuffer
- -- android如下
- local filePath = callJava()
- local addr = io.open(filePath,"rb")
- protobuffer = addr:read "*a"
- addr:close()
- protobuf.register(protobuffer)
最近Google产品及服务全面禁封 表示对国内互联网管控的表示吐槽 但是好的技术成果是无界的(我对protobuf的使用一如既往,如有想用的,请代理去下载吧) 对protobuf的使用总结
1)发现数据传输上字节上特别节省轻量,从这个优势上传输速度明显快过其他如json,尤其适合游戏通信,如果是考虑到用户通信流量及带宽资源节省问题可以考虑
2)一点不好就是客户输出数据不全估计是pbc反序列化优化table对象问题 (和后端交互数据全靠java写的小客户端日志输出查看,只是为了方便查看后端返回数据) 然后回lua项目进行处理信息
转载一些自己感觉好的文章,只是为了记录,以后查找方便,大家尽量去阅读原文。
原文地址:http://blog.csdn.net/vpingchangxin/article/details/24458051