void* TigerThread::thread_funcation(void *arg) { ODSocket *pSocket = ODSocket::sharedODSocket(); pSocket->Init(); pSocket->Create(AF_INET, SOCK_STREAM,0); /* ///////////////////////////////////////////// char ipaddr[20]; cSocket.DnsParse("www.baidu.com", ipaddr); //192.168.22.154 //aliyun-027.btcsky.com /////////////////////////////////////////////--DNS解析 www->ip */ if (pSocket->Connect("58.83.190.220", 6621)) { char recvBuf[1024] = "\0"; // std::string testmsg= |login|[email protected],e10adc3949ba59abbe56e057f20f883e,68:A8:6D:10:66:DC|$\r\n std::string testmsg= pSocket->msg_To_Sever; pSocket->Send(testmsg.data(),testmsg.length(),0); pSocket->Recv(recvBuf,1024,0); std::string rec_msg=std::string(recvBuf); printf("%s",rec_msg.c_str()); } else { CCLog("服务器连接失败"); } pSocket->Close(); pSocket->Clean(); return NULL; }
//接收数据线程 void netSocketManger::reciveThread() { char buff[MAX_BUFF]; int recv_len = 0; bool hasMorePackets = false; while(true) { if( !hasMorePackets ) { int ret = cSocket.Recv(buff, MAX_BUFF - recv_len, 0); if (ret <= 0) { isConnect = false; SocketData *errorData = newSocketData(); errorData->eventType = DISCONNECT; m_mainQueue.Push(errorData); break; } if(ret < 1) break; } T_MSGHEAD_T reciveCmd; reciveCmd.len = 1; //接收缓存中的前64个字节数据 reciveCmd.enc = 0; //数据是否加密标志 reciveCmd.com = 0; //数据是否压缩标志,这两个我们都设置为否,因为我们的数据本身只有一位 reciveCmd.idx = (uInt)m_sn; //包索引也设置为固定值,因为我们只有一个接口,这里发arduino马上就会回. reciveCmd.tea = 0; unsigned int pos = 0; SocketData *data = newSocketData(); data->module.cmd = 100; //先将100设置为灯的协议号 data->module.eno = 0; //主动将错误码设置为0,即正常 data->eventType = RESPONSE; data->sn = reciveCmd.idx; std::string datax(&buff[pos],reciveCmd.len); data->body = std::string(datax); pos += reciveCmd.len; data->bodyLen = reciveCmd.len; log("接收:%s",data->body.c_str()); log("*************************************************"); log("*************************************************"); m_mainQueue.Push(data); hasMorePackets = false; } }
//recv线程需要负责网络检测,重连。 static void* recvTask(void* data) { while (true) { if(g_NetworkStat == NetworkStat_NotConnect) { //发起网络连接 if(connectToServer()) { //连接成功,修改相应状态 g_NetworkStat = NetworkStat_Connected; //recv线程初始化为check状态 g_RecvThreadStat = RecvThreadStat_Check; continue; } else { lfSleep(2000); continue; } } //if(g_RecvThreadStat == RecvThreadStat_Check) //{ // //通过select检测网络状态 // fd_set fdset; // FD_ZERO(&fdset); // FD_SET(cSocket.getSock(), &fdset); // struct timeval timev; // timev.tv_sec = 0; // timev.tv_usec = 0; // //非阻塞select // int ret = select(cSocket.getSock() + 1, &fdset, 0, 0, &timev); // if(ret == 0) // { // //一切正常休息一下 // lfSleep(250); // } // else // { // //有recv fdset有返回,在没有发送请求包的情况下,只能是网络断掉了 // closeConnection(); // // 通知接收数据出错 // GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Conncet_Err,NULL,NULL)); // continue; // } //} //else if(g_RecvThreadStat == RecvThreadStat_Recv) { CCLog("recvTask : recv data ....."); // 读取头部 char* head = new char[sizeof(SPHead)]; int l = cSocket.Recv(head,sizeof(SPHead),0); if ( l != sizeof(SPHead)) { CCLog("recvTask : recv Head error , total length = %d, readed length = %d",sizeof(SPHead),l); // 通知接收数据出错 if(g_RecvThreadStat == RecvThreadStat_Check) { CCLog("recvTask : recv Head error,g_RecvThreadStat == RecvThreadStat_Check"); GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Conncet_Err,NULL,NULL)); } else { CCLog("recvTask : recv Head error,g_RecvThreadStat != RecvThreadStat_Check"); GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Recv_Err,NULL,NULL)); } delete head; // 出问题了 closeConnection(); continue; } if (!isHeadValied((SPHead*)head)) { CCLog("recvTask : recv Head is inValied"); // 通知接收数据出错 // 通知接收数据出错 if(g_RecvThreadStat == RecvThreadStat_Check) { CCLog("recvTask : recv Head is inValied g_RecvThreadStat == RecvThreadStat_Check"); GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Conncet_Err,NULL,NULL)); } else { CCLog("recvTask : recv Head is inValied g_RecvThreadStat != RecvThreadStat_Check"); GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Recv_Err,NULL,NULL)); } delete head; //出问题了 closeConnection(); continue; } CCLog("recvTask : recv head success!"); // 获取数据包 int data_len = ntohl(((SPHead*)head)->data_len); char* body = new char[data_len]; int l_body = cSocket.Recv(body,data_len,0); if ( l_body != data_len) { CCLog("recvTask : recv body error , total length = %d, readed length = %d",data_len,l_body); // 通知接收数据出错 // 通知接收数据出错 if(g_RecvThreadStat == RecvThreadStat_Check) { CCLog("recvTask : recv body error,g_RecvThreadStat == RecvThreadStat_Check"); GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Conncet_Err,NULL,NULL)); } else { CCLog("recvTask : recv body error,g_RecvThreadStat != RecvThreadStat_Check"); GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Recv_Err,NULL,NULL)); } delete body; delete head; //出问题了 closeConnection(); continue; } CCLog("recvTask : recv body success!"); // 通知接收数据成功 GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_RecvData,head,body)); //修改标志 g_RecvThreadStat = RecvThreadStat_Check; } /*else { CCAssert(false, "stat error"); lfSleep(1000); continue; }*/ } return 0; }
void MapScene::clientR() { ODSocket cSocketR; cSocketR.Init(); cSocketR.Create(AF_INET,SOCK_STREAM,0); while(!cSocketR.Connect(ip.c_str(),portW)) { #ifdef WIN32 Sleep(1000); #else usleep(1000 * 1000); #endif } //因为是client 所以用的是portR; char buf[BLOCK_SIZE]; for (;;) { if (!start) return ; int len = cSocketR.Recv(buf,BLOCK_SIZE ,0); if (len <= 0 ) { heartBeat = false; break; } if (!status) break; int pAngle; int x; int y; int avatarId; int type = 0; int number; bool flag[MAX][4][20]; int t_life = 0; int state = 0; avatarId = getIntFromStr(buf, 1); state = getIntFromStr(buf+1, 1); t_life = getIntFromStr(buf+2, 2); pAngle = getIntFromStr(buf+4, 4); x = getIntFromStr(buf+8, 4); y = getIntFromStr(buf+12, 4); avatar[avatarId]->pAngle = pAngle; avatar[avatarId]->getsprite()->setRotation(pAngle); avatar[avatarId]->getsprite()->setPosition(ccp(x,y)); if (!avatar[avatarId]->getsprite()->getIsVisible() && status) avatar[avatarId]->getsprite()->setIsVisible(true); len = 16; if (state == 1 && !player->isFrozen) { player->isFrozen = true; schedule(schedule_selector(MapScene::freezeplayer), 0.1f); schedule(schedule_selector(MapScene::revertplayer), 2.0f); } if (t_life < player->life) { if (player->life == t_life + 5) { schedule(schedule_selector(MapScene::attackByBomb),0.1f); } reduceLife(t_life); player->life = t_life; schedule(schedule_selector(MapScene::syncLife), 0.1f); } for (int i = 0 ; i < MAX ; ++i) for (int j = 0 ; j <= 2; ++j) for (int k = 0 ; k < avatarBullets[i][j]->capacity(); ++k) flag[i][j][k] = false; while(1) { type = getIntFromStr(buf+len, 1); if (type == 9) break; len += 1; number = getIntFromStr(buf+len, 2); len += 2; pAngle = getIntFromStr(buf+len, 4); len += 4; x = getIntFromStr(buf+len, 4); len += 4; y = getIntFromStr(buf+len, 4); len += 4; GameBullet * mybullet = (GameBullet *)(avatarBullets[avatarId][type]->objectAtIndex(number)); mybullet->vAngle = pAngle; mybullet->getsprite()->setRotation(pAngle); mybullet->getsprite()->setPosition(ccp(x,y)); if (!mybullet->getsprite()->getIsVisible()) mybullet->getsprite()->setIsVisible(true); flag[avatarId][type][number] = true; } for (int i = 0 ; i < MAX ; ++i) for (int j = 0 ; j <= 2; ++j) for (int k = 0 ; k < avatarBullets[i][j]->capacity(); ++k) { if (!flag[i][j][k]) { ((GameBullet *)(avatarBullets[i][j]->objectAtIndex(k)))->getsprite()->setIsVisible(false); } } if (t_life == 0) break; } cSocketR.Close(); cSocketR.Clean(); }
//http://www.tuicool.com/articles/YNZ7Jj void* ResPonseThread::threadFunc(void *arg) { ResPonseThread* thred=(ResPonseThread*)arg; ODSocket csocket = SocketThread::GetInstance()->getSocket(); if(SocketThread::GetInstance()->state==0) { while (true) { //have message come if (csocket.Select() == -2) { //deduct 2 head_length, unsigned char recvLen[2]; //must less 65535 bytes memset(recvLen, 0, sizeof(recvLen)); int actualRecvLen = csocket.Recv((char*)recvLen, sizeof(recvLen), 0); //log("actualRecvLen = %d", actualRecvLen); if (HEAD_LEN == actualRecvLen) { //the rest data int tLen = ((int)recvLen[0] << 8) + recvLen[1]; char* recvBuf = new char[tLen]; memset(recvBuf, 0, tLen); int recvResult = csocket.Recv(recvBuf, tLen, 0); std::string resultJson(recvBuf, tLen); log(" recveBuf =======> %s ", recvBuf); delete[] recvBuf; recvBuf = nullptr; //json parse do { rapidjson::Document *_doc = new rapidjson::Document; _doc->Parse<0>(resultJson.c_str()); CC_BREAK_IF(_doc->HasParseError()); if (!_doc->IsObject()) break; if (_doc->HasMember("Type")) { //to do const rapidjson::Value &pType = _doc->operator[]("Type"); std::string type = pType.GetString(); Director::getInstance()->getScheduler()->performFunctionInCocosThread([=]() { Director::getInstance()->getEventDispatcher()->setEnabled(true); if (type == "LoginResult") { Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(FIND_DEVICE_MSG, (void *)_doc); } else if (type == "Joystick") { Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(CONTROLLER_JOYSTICK_MSG, (void *)_doc); } else if (type == "Shock") { Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(CONTROLLER_SHOCK_MSG, (void *)_doc); } else if (type == "SwapPositionResult") { Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(CUSTOM_SWAP_POSITION_MSG, (void *)_doc); } else if (type == "ResponseJoystickStatus") { Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(REPORT_JOYSTICK_STATUS_MSG, (void *)_doc); } delete _doc; }); } else { delete _doc; } } while (0); } else { //log("ResPonseThread::threadFunc(void *arg) : exit !!! 2"); ////disconnect //break; } }//if (csocket.Select() == -2) //close socket -> exit thread ! if (thred->isExit()) { log("ResPonseThread::threadFunc(void *arg) : thred->isExit()"); break; } }//while (true) }//if(SocketThread::GetInstance()->state==0) return NULL; }