一个基本流程
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);
}
}