【Cocos2d-x】coocs2d-x + scoket 解析Json 流程总结
发布日期:2021-06-28 22:16:20 浏览次数:2 分类:技术文章

本文共 2376 字,大约阅读时间需要 7 分钟。

一个基本流程

1.组装json

void NetDataSend::sendChat(char type, int playerId, int itemIndex, string infoStr){

    Json::Value root;

    root["type"] = type;

    root["playerId"] = playerId;

    root["itemIndex"] = itemIndex;

    root["info"] = infoStr;

    root["index"] = C_CHAT;//指令号1001

    root["opIndex"] = 0;

    string info =root.toStyledString();

2.发送指令

    writeCmd(C_CHAT,info);

}

void NetDataSend::writeCmd(int code, string info){

const char *data=info.c_str();

int size=info.size();

CGameNetBean::sharedNetBean()->writeCmd(code,data,size);//发送指令

NetWaitManager::getInstance()->checkNetWait(code);//根据发送指令,判断是否有需要等待的回复指令,有则添加到等待列表中

}

3.实时监测接受指令

void NetDataReceive::updateNetDate()

{

if(mNetDataList.size()>0){

for(unsigned int i=0;i<mNetDataList.size();i++){

string data=mNetDataList[i];

int index=data.find("|");

int code=getCode(data,index);

string json=getJson(data, index);

4.接收到就解析指令

syncDispatch(code,json);

NetWaitManager::getInstance()->removeWaitCode(code);//移除等待列表中的指令

}

mNetDataList.clear();

}

}

void NetDataReceive::syncDispatch(int32_t code, string json)

{

Json::Reader reader; 

Json::Value root;

if(!reader.parse(json, root)){//解析失败

if (strlen(json.c_str())>10*1024)

{

CCLOG("===========>parse json error jsonstr: %s",json.c_str());

}else{

CCLOG("===========>parse json error code: %i",code);

}

return;

}

switch (code){

 case S_CHAT:

        {

//解析json

            this->toChat(root);

        }

            break;

}

}

void NetDataReceive::toChat( Json::Value root ){

S_Chat* sChat = new S_Chat();

sChat->type=root["type"].asInt();

sChat->sayPlayerId=root["sayPlayerId"].asInt();

sChat->sayRoleName=root["sayRoleName"].asString();

sChat->saySex=root["saySex"].asInt();

sChat->receiverPlayerId=root["receiverPlayerId"].asInt();

sChat->receiverRoleName=root["receiverRoleName"].asString();

sChat->info=root["info"].asString();

sChat->vipLv=root["vipLv"].asInt();

//UI界面使用数据

 mChatInfo = new ChatInfo();

    mChatInfo->info = m_chat->info;

//    mChatInfo->itemBean = m_chat->itemBean;

    mChatInfo->receiverPlayerId = m_chat->receiverPlayerId;

    mChatInfo->receiverRoleName = m_chat->receiverRoleName;

    mChatInfo->sayPlayerId = m_chat->sayPlayerId;

    mChatInfo->sayRoleName = m_chat->sayRoleName;

    mChatInfo->saySex = m_chat->saySex;

    mChatInfo->type = m_chat->type;

    mChatInfo->vip = m_chat->vipLv;

    CCLOG("mChatInfo->vip == > %d",mChatInfo->vip);

    ChatBoardUI* mChatBoardUI=ChatBoardUI::getInstance();

    if (mChatBoardUI) {

        mChatBoardUI->updateUI(mChatInfo);

    }

}

转载地址:https://blog.csdn.net/yhhwatl/article/details/21800237 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【Cocos2d-x】cocos2d-x + socket
下一篇:【IOS】审核被拒 Advertising

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月10日 06时30分12秒