void netSocketManger::endSocket()
{
    if (!threadSend.joinable()) {//线程已启动
        threadSend.~thread();
        delete m_sendEvent;
        m_sendEvent = NULL;
        
    }
    if (!threadRecive.joinable()) {
        threadRecive.~thread();
    }

    while (!m_sendQueue.IsEmpty()) {
        SocketData *sendData = m_sendQueue.Pop();
        //CC_SAFE_FREE(sendData->body);
        free(sendData);
    }
    
    while (!m_mainQueue.IsEmpty()) {
        SocketData *mainData = m_mainQueue.Pop();
        CC_SAFE_FREE(mainData);
        //CC_SAFE_FREE(mainData->addContent);
    }
    
    if (isConnect) {
        cSocket.Close();
        cSocket.Clean();
        isConnect = false;
    }
    m_isFirst = true;
    m_sendDelegateList.clear();
}
예제 #2
0
void closeConnection()
{
	if (cSocket.Close() != 0)
	{
		CCLog("ODSocket :closeConnection Close Error,errCode = %d!",cSocket.GetError());
	}
	if (cSocket.Clean() != 0)
	{
		CCLog("ODSocket :closeConnection Clean Error,errCode = %d!",cSocket.GetError());
	}
	//
	g_NetworkStat = NetworkStat_NotConnect;
	CCLog(" -----Network closed-----");
	//
	g_NetworkStat = NetworkStat_NotConnect;


	MessageAutoLock lock;
	RequestMessage* temp;
	int count = 0;
	while(!requestMsgQueue.empty())
	{
		count ++;
		temp = requestMsgQueue.front();
		requestMsgQueue.pop();
		delete temp;
	}
	CCLog("%s --> throwed %d request packet(s)",__FUNCTION__,count);


	// 这也不需要,因为ODSocket::Clean()有调用这个函数
//#ifdef WIN32
//	WSACleanup();
//#endif
}
예제 #3
0
void connectSocket(ODSocket &mysocket){

	mysocket.Init();
	mysocket.Create(AF_INET,SOCK_STREAM,0);
	mysocket.Bind(7880);
	mysocket.Listen(500);
	//mysocket.setMode(1);
}
예제 #4
0
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::connectSocket()
{
    
    if (!isConnect) {
        cSocket.Init();
        cSocket.Create(AF_INET,SOCK_STREAM,0);
        if (m_sendEvent == NULL) {
            m_sendEvent = new CEvent();
        }
        
        s_tea = 0;
        threadSend = std::thread(&netSocketManger::sendThread,this);//创建一个分支线程,回调到sendThread函数里
        threadSend.detach();
    }
    
    log("send thread is run");
}
예제 #6
0
void* SocketThread::start_thread(void *arg)   {  
	SocketThread* thred=(SocketThread*)arg;
	ODSocket cdSocket;
	cdSocket.Init();	
	bool isok=cdSocket.Create(AF_INET,SOCK_STREAM,0);	
//	bool iscon=cdSocket.Connect("127.0.0.1",8000);
    bool iscon=cdSocket.Connect("192.168.0.144",8000);
	if(iscon){
		thred->state=0;
		ResPonseThread::GetInstance()->start();//// 启动响应参数
		CCLOG("conection");
	}else{
		thred->state=1;
	}	
	thred->csocket=cdSocket;
	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;
        
    }
    
}
//主线程更新
void netSocketManger::update(float dt)
{
    if (!m_mainQueue.IsEmpty()) {
        SocketData *data = m_mainQueue.Pop();
        
        if (data->eventType == REQUEST) {
            if (m_pushDelegate) {
                m_pushDelegate->pushHandler(data);
            }
        }else if (data->eventType == RESPONSE) {
            SendDelegateMap::iterator it = m_sendDelegateList.find(data->sn);
            if (it != m_sendDelegateList.end()) {
                SendDataDelegate *delegate = it->second;
                m_sendDelegateList.erase(it);
                delegate->sendHandler(data);
            }
        }else if (data->eventType == CONNECT_SUCCEED || data->eventType == CONNECT_FAIL || data->eventType == DISCONNECT) {
            if (data->eventType != CONNECT_SUCCEED) {
                if (!threadSend.joinable()) {//线程已启动
                    threadSend.~thread();
                    delete m_sendEvent;
                    m_sendEvent = NULL;
                    
                }
                if (!threadRecive.joinable()) {
                    threadRecive.~thread();
                }
                
                while (!m_sendQueue.IsEmpty()) {
                    SocketData *sendData = m_sendQueue.Pop();
                    //litaoming update
                    //CC_SAFE_FREE(data->body);
                    //CC_SAFE_FREE(sendData->reciveBody);
                    free(sendData);
                }
                
                while (!m_mainQueue.IsEmpty()) {
                    SocketData *mainData = m_mainQueue.Pop();
                    if (mainData != data) {
                        //CC_SAFE_FREE(mainData->body);
                        //CC_SAFE_FREE(mainData->addContent);
                    }
                    
                }
                if (isConnect) {
                    cSocket.Close();
                    cSocket.Clean();
                    isConnect = false;
                }
                m_isFirst = true;
                m_sendDelegateList.clear();
            }
            if (m_statusDelegate) {
                m_statusDelegate->statusHandler(data->eventType);
            }
        }
        //CC_SAFE_FREE(data->body);
        //CC_SAFE_FREE(data->addContent);
        free(data);
    }
}
예제 #9
0
//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;
	
}
예제 #10
0
// 负责发送数据,发送成功后修改接受线程的状态为recv,让接受线程开始接受请求返回包(心跳+数据包都是)
static void* sendTask(void* data)
{
	while (true)
	{
		//如果接收线程当前还在收上一个请求包的响应则不再发送新的请求
		if(g_RecvThreadStat == RecvThreadStat_Recv)
		{
			lfSleep(100);
			continue;
		}

		//如果需要心跳,则先心跳。否则才从队列中取请求包
		int time_gap = time(0) - g_LastHeartBeatTime;
		RequestMessage* msg = NULL;
		if(time_gap >= HeartBeatTimeGap && g_HeartBeatMsg != NULL)
		{
			//更新时间
			g_LastHeartBeatTime = time(0);

			msg = new RequestMessage(g_HeartBeatMsg);
		}
		else
		{
			// 加锁
			pthread_mutex_lock(&requestMsgQueueMutex);
			if (requestMsgQueue.empty())
			{
				// 解锁
				pthread_mutex_unlock(&requestMsgQueueMutex);
			}
			else
			{
				msg = requestMsgQueue.front();
				requestMsgQueue.pop();

				// 解锁
				pthread_mutex_unlock(&requestMsgQueueMutex);
			}
		}

		//当前没有需要发送的请求
		if(msg == NULL)
		{
			lfSleep(100);
			continue;
		}

		//发送
		{
			//判断当前网络是否连上
			if(g_NetworkStat == NetworkStat_NotConnect)
			{
				CCLog("%s:%d --> g_NetworkStat == NetworkStat_NotConnect post send error",__FUNCTION__,__LINE__);

				// 通知发送数据出错
				GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Send_Err,NULL,NULL));

				delete msg;

				continue;
			}

			CCLog("sendTask : send data .....");
			int l = cSocket.Send(msg->getData(),msg->getDataLength(),0);
			//
			if ( l != msg->getDataLength())
			{
				CCLog("sendTask : send data error! length = %d, sended length = %d",msg->getDataLength(),l);

				// 通知发送数据出错
				GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Send_Err,NULL,NULL));

				delete msg;

				//出问题了
				closeConnection();

				continue;
			}
			else
			{
				delete msg;

				//发送成功,修改recv线程的标志
				g_RecvThreadStat = RecvThreadStat_Recv;

				CCLog("sendTask : send data success");
			}
		}
	}
	return 0;
}
예제 #11
0
bool connectToServer()
{
	if (g_NetworkStat != NetworkStat_NotConnect)
		return true;

	if (cSocket.Init() == -1)
	{
		CCLog("\n==============================================================");
		CCLog("ODSocket: connectToServer Init error,errorCode = %d!", cSocket.GetError());
		CCLog("==============================================================\n");
		// 通知链接失败
		GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Conncet_Err,NULL,NULL));
		return false;
	}
	if (cSocket.Create(AF_INET,SOCK_STREAM,0) == false)
	{
		CCLog("\n==============================================================");
		CCLog("ODSocket: connectToServer Create error,errorCode = %d!",cSocket.GetError());
		CCLog("==============================================================\n");

		// 通知链接失败
		GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Conncet_Err,NULL,NULL));
		return false;
	}
	if (cSocket.Connect(NetWorkThreadProc::getProc()->getCurrentIp(),NetWorkThreadProc::getProc()->getCurrentPort()) == false)
	{
		CCLog("\n==========================================================================");
		CCLog("ODSocket: connectToServer[%s:%d] Connect error,errorCode = %d!",NetWorkThreadProc::getProc()->getCurrentIp(),NetWorkThreadProc::getProc()->getCurrentPort(),cSocket.GetError());
		CCLog("============================================================================\n");

		closeConnection();

		// 通知链失败
		GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Conncet_Err,NULL,NULL));

		return false;
	}
	CCLog("\n\n");
	CCLog("\n==============================================================");
	CCLog("ODSocket : connectToServer %s-%d Success!",NetWorkThreadProc::getProc()->getCurrentIp(),NetWorkThreadProc::getProc()->getCurrentPort());
	CCLog("==============================================================\n");
	CCLog("\n\n");
	//cSocket.setT

	//设置状态
	g_NetworkStat = NetworkStat_Connected;

	// 设置超时
	{
		cSocket.SetRecvTimeOut(RECV_TIME_OUT);
		cSocket.SetSendTimeOut(SEND_TIME_OUT);
	}

	// 这个在init时已经调用了,这里不需要了,而且WSAStartup应该是winSocket第一个调用的函数
	// 所以写在这里也是不对的
//#ifdef WIN32
//	WORD wVersionRequested;
//	WSADATA wsaData;
//	int err;
//
//	/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
//	wVersionRequested = MAKEWORD(2, 2);
//
//	err = WSAStartup(wVersionRequested, &wsaData);
//	if (err != 0) {
//		/* Tell the user that we could not find a usable */
//		/* Winsock DLL.                                  */
//		CCLog("WSAStartup failed");
//
//		closeConnection();
//
//		return false;
//	}
//#endif

	// 通知链接成功
	GlobalNetworkMsgDispacher::getMsgDispacher()->addPakage(new GlobalNetPackage(Type_Conncet_Suc,NULL,NULL));

	return true;
}
//发送数据线程
void netSocketManger::sendThread()
{

    //bool connect = cSocket.Connect(kServerIP,kServerPort);
    bool connect = cSocket.Connect(netSocketManger::sharednetSocketManger()->server.IP.c_str(),netSocketManger::sharednetSocketManger()->server.port);
   // cSocket.Send("bbb",strlen("bbb")+1,0);

    if (connect) {
        isConnect = true;
        SocketData *errorData = newSocketData();
        errorData->eventType = CONNECT_SUCCEED;
        m_mainQueue.Push(errorData);
        //创建接收线程
        m_mutexx.lock();
        netSocketManger::sharednetSocketManger()->createReciveThread();
        m_mutexx.unlock();
        m_sendEvent->Lock();
        while (true) {
            while (!m_sendQueue.IsEmpty()) {
                SocketData *data = m_sendQueue.Pop();
                uLong comprLen = data->bodyLen;
                const char *compr = data->sendData;
                
                T_MSGHEAD_T msgHead;
                
                msgHead.cmd = (unsigned short)data->module.cmd;
                msgHead.com = 0;
                msgHead.enc = 0;
                msgHead.eno = 0;
                msgHead.idx = (uInt)data->sn;
                msgHead.len = (unsigned short)comprLen;
                msgHead.tea = 0;//s_tea;
                
                unsigned char *sendData = (unsigned char*)malloc(comprLen);
                unsigned int pos = 0;
                
                memcpy(&sendData[pos], compr, comprLen);//body
                pos += comprLen;
                
                int ret = cSocket.Send((char*)sendData,pos,0);
                log("发送:%s",compr);
                if (ret <= 0) {
                    m_sendEvent->Unlock();
                    free(sendData);
                    SocketData *errorData = newSocketData();
                    errorData->eventType = DISCONNECT;
                    m_mainQueue.Push(errorData);
                    return;
                }

                free(data->sendData);
                free(data);
                free(sendData);

                log("-----发送数据长度len:%d------",msgHead.len);
                log("-----------");
                
            }
            
            m_sendEvent->Wait();
        }
        m_sendEvent->Unlock();
    }else {
        isConnect = false;
        SocketData *errorData = newSocketData();
        errorData->eventType = CONNECT_FAIL;
        m_mainQueue.Push(errorData);
    }
}
예제 #13
0
//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;
}
bool DeviceControllerScene::init()
{
	if (!Layer::init())
	{
		return false;
	}
	auto m_deviceDataVector = DeviceData::getInstance()->getDataVector();
	log("m_deviceDataVector.size() = %d", m_deviceDataVector.size());

	auto layer = CSLoader::createNode("helper_device_layer.csb");
	auto layoutBG = layer->getChildByName("layout_bg");
	auto baseLayout = layoutBG->getChildByName("base_layout");
	//refind button
	auto buttonQr = (Button*)baseLayout->getChildByName("button_qr");
	//buttonQr->setVisible(false);//大厅1.3.6之前屏蔽扫码
	buttonQr->addClickEventListener([=](Ref *ref)
	{
//		JniOpenSanQr();
        std::vector<Contacts> mContacts;
        getPhoneContacts(mContacts);

	});
	//refind button
	auto refindButton = (Button*)baseLayout->getChildByName("paired_button");
	refindButton->addClickEventListener([=](Ref *ref)
	{
		Director::getInstance()->replaceScene(TransitionSlideInL::create(TRANSITION_TIME, FindDeviceScene::createScene()));
	});
	//open controller button
	auto downLayout = layoutBG->getChildByName("down_layout");
	auto openControllerButton = (Button*)downLayout->getChildByName("open_controller_button");
	CCLOG("openControllerButton Size [%.2f, %.2f]", openControllerButton->getContentSize().width, openControllerButton->getContentSize().height);
	openControllerButton->addClickEventListener([=](Ref* ref)
	{
		//gameSocket(m_deviceDataVector[index].ip.c_str(), stoi(m_deviceDataVector[index].port[0]));
		//10_0_4_251#9527_9528_9529_9530
		auto tLastNode = getNode();
		if (tLastNode)
		{
			addConnectingLayout();
			int tIndex = tLastNode->getTag();
			connect(m_deviceDataVector[tIndex].ip.c_str(), atoi(m_deviceDataVector[tIndex].port.c_str()));
		}
	});
	//disable
	openControllerButton->setBright(false);
	openControllerButton->setTouchEnabled(false);

	//ListView
	auto listviewLayout = baseLayout->getChildByName("listview_layout");
	auto listview = listviewLayout->getChildByName("listview");
    Size listviewSize = listview->getContentSize();
	
	if(m_deviceDataVector.size() > 0)
	{
		//find nothing...
		auto findNothingText = listviewLayout->getChildByName("find_nothing_text");
		findNothingText->setVisible(false);
		int buttonTag = 0;
		int selectLogoTag = 0;
		float delayTime = 0.0f;
		for (auto deviceData : m_deviceDataVector) {
			//button
			auto button = Button::create("normal_gray_button.9.png",
					"select_gray_button.9.png");
			button->setScale9Enabled(true);
            button->setContentSize(cocos2d::Size(listviewSize.width, 80));
			button->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
			//button->setPosition();
			//button->setTitleText(deviceData.name);
			//button->setTitleColor(Color3B::WHITE);
			button->setVisible(false);
			button->setTag(buttonTag++);
			delayTime = ++delayTime / 2.0f;
			button->runAction(Sequence::createWithTwoActions(DelayTime::create(delayTime), CallFunc::create([button](){button->setVisible(true); })));
			button->addTouchEventListener([=](Ref *ref, Widget::TouchEventType eventType)
			{
				if (Widget::TouchEventType::ENDED == eventType)
				{
					Button *tButton = (Button*)ref;
					int buttonTag = tButton->getTag();
					log("button->getTag = %d", buttonTag);
					//reset old select
					auto tLastNode = getNode();
					if (tLastNode)
					{
						tLastNode->setVisible(false);
					}
					//set new select
					auto select = button->getChildByTag(buttonTag);
					select->setVisible(true);
					setNode(select);

					//Enabled
					openControllerButton->setBright(true);
					openControllerButton->setTouchEnabled(true);

				}
			});

			//buttonSize
			cocos2d::Size buttonSize = button->getContentSize();

			//icon
			auto icon = Sprite::create("highlight_icon.png");
			//icon->setScale(0.5f);
			icon->setPosition(Vec2(buttonSize.width / 7.5, buttonSize.height / 2));
			button->addChild(icon);

			//name
			auto name = Text::create(deviceData.name, "", FONT_SIZE);
			name->setPosition(Vec2(buttonSize.width / 4.0f, buttonSize.height / 2));
			name->setColor(Color3B::BLACK);
			name->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
			cocos2d::Size nameSize = name->getContentSize();
			name->ignoreContentAdaptWithSize(false);
            name->setTextAreaSize(cocos2d::Size(342.0f, buttonSize.height));
			name->setTextVerticalAlignment(TextVAlignment::CENTER);
			button->addChild(name);

			//select logo
			auto selectLogo = Sprite::create("select_logo.png");
			selectLogo->setPosition(Vec2(buttonSize.width * 0.9f, buttonSize.height / 2));
			selectLogo->setVisible(false);
			selectLogo->setTag(selectLogoTag++);
			button->addChild(selectLogo);
			listview->addChild(button);
		}

	}
	
	
	//wifi
	mTextWifi = (Text*)layoutBG->getChildByName("wifi_layout")->getChildByName("wifi_text");
	setWifiState(false);
	

	

	//more info button
	auto moreInfoButton = (Button*)downLayout->getChildByName("more_info_button");
	CCLOG("moreInfoButton Size [%.2f, %.2f]", moreInfoButton->getContentSize().width, moreInfoButton->getContentSize().height);
	moreInfoButton->addClickEventListener([=](Ref *ref)
	{
		Director::getInstance()->replaceScene(TransitionSlideInR::create(TRANSITION_TIME, MoreScene::createScene()));
	});
	addChild(layer);

	//解析连接返回结果
	getEventDispatcher()->addCustomEventListener(FIND_DEVICE_MSG, [&](EventCustom * event)
	{
		rapidjson::Document *data = (rapidjson::Document *)event->getUserData();

		const rapidjson::Value &pCode = data->operator[]("Code");
		const rapidjson::Value &pPosition = data->operator[]("Position");
		int code = pCode.GetInt();
		int position = pPosition.GetInt();
		log("code = %d, position = %d", code, position);
		if (code == 0)
		{
			auto deviceData = DeviceData::getInstance();
			deviceData->setGloudVersionNameInteger(0);//避免扫描时没重置
			/*
			 * 1.2.0(含)之前的版本没有VersionName字段,
			 *  为了兼容大厅和小格旧版本,
			 *  收到 responseForRequest == 0 发送一条消息,
			 *  收到 responseForRequest == 1 才进入手柄界面
			 */
			if(data->HasMember("ResponseForRequest"))
			{
				//VersionName获取数字再转int
				std::string versionName = get_all_number(data->operator[]("VersionName").GetString());
				int responseForRequest = data->operator[]("ResponseForRequest").GetInt();
				log("versionName = %s, responseForRequest = %d", versionName.c_str(), responseForRequest);
				if(versionName.size() > 0)
				{
					deviceData->setGloudVersionName(data->operator[]("VersionName").GetString());
					deviceData->setGloudVersionNameInteger(atoi(versionName.c_str()));
				}
				if (data->HasMember("Version"))
				{
					deviceData->setGloudVersion(data->operator[]("Version").GetUint());
				}
				if (data->HasMember("Channel"))
				{
					deviceData->setGloudChannel(data->operator[]("Channel").GetString());
				}
				if (data->HasMember("AccountID"))
				{
					deviceData->setGloudAccountID(data->operator[]("AccountID").GetInt());
				}
				if (data->HasMember("DeviceUUID"))
				{
					deviceData->setGloudDeviceUUID(data->operator[]("DeviceUUID").GetString());
				}
				if (data->HasMember("LoginToken"))
				{
					deviceData->setGloudLoginToken(data->operator[]("LoginToken").GetString());
				}
				if(responseForRequest == 0)
				{
					log("SocketThread::GetInstance()->state = %d", SocketThread::GetInstance()->state);
					if(0 == SocketThread::GetInstance()->state)
					{
						ODSocket csocket = SocketThread::GetInstance()->getSocket();
						std::string sendMsg = StringUtils::format("{\"Type\":\"LoginRequest\",\"Version\":%d,\"Name\":\"%s\"}",JniGetClientVersionCode(),JniGetPhoneModel().c_str());
						log("socket::send: %s", sendMsg.c_str());
						csocket.SendToJava(sendMsg.c_str(), sendMsg.length(), 0);
					}
				}
				else
				{
					deviceData->setPosition(position);
					Director::getInstance()->replaceScene(TransitionSlideInR::create(TRANSITION_TIME, VgcScene::createScene()));
				}
			}
			else
			{
				deviceData->setPosition(position);
				Director::getInstance()->replaceScene(TransitionSlideInR::create(TRANSITION_TIME, VgcScene::createScene()));
			}
		}
		else
		{
			//no position
			delConnectingLayout();
			showDialog(xmlParser["tip_title"], xmlParser["tip_msg"], xmlParser["ok_button"]);
		}
	});

	//提示连接失败
	getEventDispatcher()->addCustomEventListener(CONNECT_DEVICE_MSG, [&](EventCustom * event)
	{
		delConnectingLayout();
		showDialog(xmlParser["no_connect_title"], xmlParser["error_connect_msg"], xmlParser["ok_button"]);
	});


	//two times exit
	auto listener = EventListenerKeyboard::create();
	listener->onKeyPressed = [&](EventKeyboard::KeyCode code, Event *event){
		if (code == EventKeyboard::KeyCode::KEY_ESCAPE)
		{
			if ((millisecondNow() - exitTime) > 2000L)
			{
				exitTime = millisecondNow();
				ToastShow(xmlParser["exit_tip"],0.5f, -90.0f);
			}
			else
			{
				Director::getInstance()->end();
			}
		}
	};
	getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
	this->setName(DEVICE_CONTROLLER_SCENE);
	return true;
}
예제 #15
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();
}
예제 #16
0
void MapScene::serverW()
{
    ODSocket cSocket;
    mysocketW.Init();
    mysocketW.Create(AF_INET,SOCK_STREAM,0);
    mysocketW.Bind(portW);
    mysocketW.Listen();
    char ipClient[64];
    while(!mysocketW.Accept(cSocket,ipClient))
    {
#ifdef WIN32
        Sleep(1000);
#else
        usleep(1000 * 1000);
#endif
    }
    char buf[BLOCK_SIZE];
    sprintf(buf,"%1d",id);
    int aid  = -1;
    int state = 0;
    while(1)
    {
        if (!start)
            break;
        for(int i = 0 ; i < MAX; ++i)
        {
            if (avatar[i]->getsprite()->getIsVisible())
            {
                aid = i;
                break;
            }
        }
        state = 0;
        if(avatar[aid]->isFrozen)
        {
            state = 1;
        }
        sprintf(buf+1,"%1d",state);
        sprintf(buf+2,"%2d",avatarLife);
        CCPoint herop = (player->getsprite())->getPosition();
        int dy = herop.y;
        int dx = herop.x;
        int angle = (int)player->pAngle;
        sprintf(buf+4, "%4d", angle);
        sprintf(buf+8, "%4d", dx);
        sprintf(buf+12, "%4d", dy);
        int len = 16;
        for (int i = 0; i <= 2; ++i)
            for (int j = 0; j < bullets[i]->capacity(); ++j)
            {
                GameBullet * mybullet = (GameBullet *)(bullets[i]->objectAtIndex(j));
                if (mybullet->getsprite()->getIsVisible())
                {
                    CCPoint p = (mybullet->getsprite()->getPosition());
                    sprintf(buf+len, "%1d", (int)i);
                    len += 1;
                    sprintf(buf+len, "%2d", (int)j);
                    len += 2;
                    sprintf(buf+len, "%4d", (int)mybullet->vAngle);
                    len += 4;
                    sprintf(buf+len, "%4d", (int)p.x);
                    len += 4;
                    sprintf(buf+len, "%4d", (int)p.y);
                    len += 4;
                }
            }
        buf[len] = '9';
        if (cSocket.Send(buf, BLOCK_SIZE ,0)== -1)
            break;
#ifdef WIN32
        Sleep(30);
#else
        usleep(30 * 1000);
#endif
    }
    mysocketW.Close();
    mysocketW.Clean();
}
예제 #17
0
void MapScene::clientW()
{
    ODSocket cSocketW;
    cSocketW.Init();
    cSocketW.Create(AF_INET,SOCK_STREAM,0);
    while(!cSocketW.Connect(ip.c_str(),portR))
    {
#ifdef WIN32
        Sleep(1000);
#else
        usleep(1000 * 1000);
#endif
    }
    ; //因为是client 所以用的是portR;
    char buf[BLOCK_SIZE];
    sprintf(buf,"%1d",id);
    int aid  = -1;
    int state = 0;

    while(1)
    {
        if (!start)
            break;
        for(int i = 0 ; i < MAX; ++i)
        {
            if (avatar[i]->getsprite()->getIsVisible())
            {
                aid = i;
                break;
            }
        }
        state = 0;
        if(avatar[aid]->isFrozen)
        {
            state = 1;
        }
        sprintf(buf+1,"%1d",state);
        sprintf(buf+2,"%2d",avatarLife);
        CCPoint herop = (player->getsprite())->getPosition();
        int dy = herop.y;
        int dx = herop.x;
        int angle = (int)player->pAngle;
        sprintf(buf+4, "%4d", angle);
        sprintf(buf+8, "%4d", dx);
        sprintf(buf+12, "%4d", dy);
        int len = 16;
        for (int i = 0; i <= 2; ++i)
            for (int j = 0; j < bullets[i]->capacity(); ++j)
            {
                GameBullet * mybullet = (GameBullet *)(bullets[i]->objectAtIndex(j));
                if (mybullet->getsprite()->getIsVisible())
                {
                    CCPoint p = (mybullet->getsprite()->getPosition());
                    sprintf(buf+len, "%1d", (int)i);
                    len += 1;
                    sprintf(buf+len, "%2d", (int)j);
                    len += 2;
                    sprintf(buf+len, "%4d", (int)mybullet->vAngle);
                    len += 4;
                    sprintf(buf+len, "%4d", (int)p.x);
                    len += 4;
                    sprintf(buf+len, "%4d", (int)p.y);
                    len += 4;
                }
            }
        buf[len] = '9';
        //if (demo > 3 || temp != 0)
        //{
        if (cSocketW.Send(buf, BLOCK_SIZE ,0)== -1)
            break;

        //	}
#ifdef WIN32
        Sleep(30);
#else
        usleep(30 * 1000);
#endif
    }
    cSocketW.Close();
    cSocketW.Clean();
}