void NetworkEngine::onGameObjectMessage( RakNet::Packet * packet ) { RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); //En otros sitios esta como bsIn.IgnoreBytes(1), es lo mismo RakNet::NetworkID id; Message message; bsIn.Read(id); bsIn.Read(message); GameObject *gameObject = replicaManager->getGameObjectByNetworkID(id); if(gameObject != NULL) { gameObject->broadcastMessage(message); } }
void NetworkEngine::experienceForPlayers(RakNet::Packet *packet) { RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); //En otros sitios esta como bsIn.IgnoreBytes(1), es lo mismo float experience; bsIn.Read(experience); Message message; message.type = Message::ADD_EXPERIENCE; message.value = experience; GameObject* receiver = GameManager::getInstance()->getGameObjectManager()->getMainPlayer(); if(receiver != NULL) { receiver->broadcastMessage(message); } }
void Commands::UpdateRaknet() { switch (mRaknet.mPacket->data[0]) { case ID_SET_SPRITE: { int sprite = 0; RakNet::BitStream bsIn(mRaknet.mPacket->data,mRaknet.mPacket->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(sprite); mPlayerInfo.SetSpriteNumber(sprite); mCharacter.UpdateSprite(); break; } } }
void WINAPI OnNote( PTP_CALLBACK_INSTANCE pInstance, void* packet) { RakNet::Packet* pIn = (RakNet::Packet*)packet; RakNet::BitStream bsIn( pIn->data, pIn->length, false); bsIn.IgnoreBytes( sizeof(RakNet::MessageID)); int ID; RakNet::RakString note_intent; bsIn.Read( ID); bsIn.Read( note_intent); char sqlCmd[2048]; sprintf( sqlCmd, "UPDATE note SET note_intent='%s' WHERE Id=%d", note_intent.C_String(), ID); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult( sqlCmd); g_globalData->databaseLock.Unlock(); g_globalData->peer->DeallocatePacket( pIn); }
void NetworkEngine::nextWave(RakNet::Packet * packet) { if(GameManager::getInstance()->getGameObjectManager()->getMainPlayer() != NULL) { Message message; message.type = Message::NEXT_WAVE; RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); //En otros sitios esta como bsIn.IgnoreBytes(1), es lo mismo int wave; bsIn.Read(wave); message.value = wave; GameManager::getInstance()->getGameObjectManager()->getMainPlayer()->broadcastMessage(message); } }
std::vector<RakNet::RakString> NetworkEngine::getLanServers() { //En el server browser se utiliza getLanServersList() std::vector<RakNet::RakString> serverList; RakNet::Packet *packet; peer->Ping("255.255.255.255", SERVER_PORT, false); RakNet::TimeMS timeout = RakNet::GetTimeMS() + 1000; while(RakNet::GetTimeMS() < timeout) // Bloquea durante 1s el juego { packet = peer->Receive(); while(packet != 0) //Ha llegado un paquete { if (packet->data[0]==ID_UNCONNECTED_PONG) { RakNet::TimeMS time; RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(1); bsIn.Read(time); //char playerData; //bsIn.Read(playerData); std::cout<<peer->NumberOfConnections()<<std::endl; //std::cout << "Server: " << packet->systemAddress.ToString() << ", players: "<< playerData << "/4, ping: "<< RakNet::GetTimeMS() - time << "ms\n"; std::cout << "Server: " << packet->systemAddress.ToString() << ", ping: "<< RakNet::GetTimeMS() - time << "ms\n"; serverList.push_back((RakNet::RakString) packet->systemAddress.ToString(false)); timeout -= 500; // Si ha encontrado un servidor termina antes } peer->DeallocatePacket(packet); packet = peer->Receive(); } RakSleep(30); } return serverList; }
void FullyConnectedMesh2::OnRequestFCMGuid(Packet *packet) { RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(MessageID)); // Only the host says who is host if (ourFCMGuid!=0 && IsHostSystem()==false) { return; } RakNetTimeUS senderElapsedRuntime; if (ourFCMGuid==0) { bsIn.Read(senderElapsedRuntime); RakNetTimeUS ourElapsedRuntime = GetElapsedRuntime(); // TODO: BUG: Multiple simultaneous connections can create a subnet. Don't respond to this until all systems answer. // Even if both systems disagree on who is host by time, the problem is avoid because of the random number for the low 4 bytes of FCM2Guid if (ourElapsedRuntime>senderElapsedRuntime) { // We are probably host // 2 is for 2 total connections // Their total connection count is one higher, so their FCM2Guid has a lower priority than ours SendFCMGuidResponse(packet->systemAddress, totalConnectionCount+1, 2); } else { // They are probably host SendFCMGuidResponse(packet->systemAddress, totalConnectionCount, 2); } } else { // totalConnectionCount is set to the value of 2 passed to SendFCMGuidResponse when our own guid is first assigned // We are host here RakAssert(totalConnectionCount!=0); SendFCMGuidResponse(packet->systemAddress, totalConnectionCount+1, totalConnectionCount+1); } }
// El cliente encuentra servidores void NetworkEngine::lanServerFound(RakNet::Packet * packet) { RakNet::TimeMS time; RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(1); bsIn.Read(time); bool serverIsInLobby = bsIn.ReadBit(); if(serverIsInLobby) //Solo muestra los que no han empezado { unsigned char numPlayers; bsIn.Read(numPlayers); ServerInfo server; server.ip = packet->systemAddress.ToString(false); server.ping = RakNet::GetTimeMS() - time ; server.players = numPlayers; server.isLan = true; if(numPlayers < 0 || numPlayers > MAX_PLAYERS) //Se ignoran los servers rotos { return; } //add server en browser if(serverBrowser.addServer(server)) { GameManager::getInstance()->getGraphicsEngine()->addServerToBrowserTable(server); } // Es un cliente que ha arrancado un servidor y esta esperando if (!GameManager::getInstance()->isServer() && waitingForServer) { // Se autoconecta a este ultimo waitingForServer = false; joinServer( serverBrowser.getServerInfoList().size() - 1 ); } } }
void Chat::Update(Packet* packet, RakPeerInterface* peer) { switch (packet->data[0]) { case ID_CHATMESSAGE: { RakString message; // Read the info BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(message); // Send message to all users RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_CHATMESSAGE); bsOut.Write(message); bsOut.Write(mCurrentPlayers.GetPlayer(packet->guid)->GetUsername()); peer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,UNASSIGNED_RAKNET_GUID, true); printf("Chat message sent to all users\n"); } } }
PluginReceiveResult FullyConnectedMesh2::OnReceive(Packet *packet) { switch (packet->data[0]) { case ID_REMOTE_NEW_INCOMING_CONNECTION: { if (connectOnNewRemoteConnections) { unsigned int count; RakNet::BitStream bsIn(packet->data, packet->length, false); bsIn.IgnoreBytes(sizeof(MessageID)); bsIn.Read(count); SystemAddress remoteAddress; RakNetGUID remoteGuid; char str[64]; for (unsigned int i=0; i < count; i++) { bsIn.Read(remoteAddress); bsIn.Read(remoteGuid); remoteAddress.ToString(false,str); rakPeerInterface->Connect(str,remoteAddress.port,connectionPassword.C_String(),(int) connectionPassword.GetLength()); } } } break; case ID_FCM2_REQUEST_FCMGUID: OnRequestFCMGuid(packet); return RR_STOP_PROCESSING_AND_DEALLOCATE; case ID_FCM2_RESPOND_CONNECTION_COUNT: OnRespondConnectionCount(packet); return RR_STOP_PROCESSING_AND_DEALLOCATE; case ID_FCM2_INFORM_FCMGUID: OnInformFCMGuid(packet); return RR_STOP_PROCESSING_AND_DEALLOCATE; } return RR_CONTINUE_PROCESSING; }
void WINAPI OnSendMail( PTP_CALLBACK_INSTANCE pInstance, void* packet) { int t; int fromUser,toDepartment,isRead,type; char sqlCmd[1024]; RakNet::Packet* pIn = (RakNet::Packet*)packet; RakNet::BitStream bsIn(pIn->data, pIn->length, false); RakNet::RakString title,content; bsIn.IgnoreBytes( sizeof(RakNet::MessageID)); bsIn.Read( fromUser); bsIn.Read( toDepartment); bsIn.Read( title); bsIn.Read( content); bsIn.Read( isRead); bsIn.Read( t); bsIn.Read( type); int option = isRead; if(option == MAILCREATE)//起草公文 { sprintf( sqlCmd, "INSERT INTO mail (fromuser,todepartment,title,t,content,isread) values (%d,%d,'%s',%d,'%s',1)", fromUser, toDepartment, title.C_String(),t,content.C_String()); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult(sqlCmd); //获取组长id sprintf( sqlCmd, "select department_master from department where id in (select department from account where id=%d)",fromUser); g_globalData->database->QueryWithResult(sqlCmd); g_globalData->database->FetchRow(); int boss = g_globalData->database->GetResultInt(0); g_globalData->databaseLock.Unlock(); //推送消息 map<int, RakNet::SystemAddress>::iterator iter; iter = g_globalData->addressMap.find( boss); if( iter != g_globalData->addressMap.end()) { RakNet::BitStream bsOutTest; bsOutTest.Write( (RakNet::MessageID)RH_SENDMAIL); bsOutTest.Write( fromUser); bsOutTest.Write( toDepartment); bsOutTest.Write( title); bsOutTest.Write( content); bsOutTest.Write( isRead); bsOutTest.Write( t); bsOutTest.Write( type); g_globalData->peer->Send( &bsOutTest, HIGH_PRIORITY, RELIABLE_ORDERED, 0, iter->second, false); printf("%d公文(1)下发\n",fromUser); } else{ printf("%d公文(1)未发送\n",fromUser); } } else if(option == MAILCHECKED)//通过审批 { sprintf( sqlCmd, "UPDATE mail SET isread=2 where fromuser=%d and t=%d and todepartment=%d and type=%d", fromUser,t,toDepartment,type); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult(sqlCmd); sprintf( sqlCmd, "SELECT id from account where department=%d",toDepartment); int count = g_globalData->database->QueryWithResult(sqlCmd); char sqlAdd[1024][100]; int toID[100]; for(int n=0;n<count;n++) { g_globalData->database->FetchRow(); toID[n] = g_globalData->database->GetResultInt(0); sprintf( sqlAdd[n], "INSERT INTO mail (fromuser,todepartment,title,t,content,isread,type) values (%d,%d,'%s',%d,'%s',4,1)" ,fromUser,toID[n],title.C_String(),t,content.C_String()); } for(int n=0;n<count;n++) { g_globalData->database->QueryWithResult(sqlAdd[n]); //推送消息 map<int, RakNet::SystemAddress>::iterator iter; iter = g_globalData->addressMap.find( toID[n]); if( iter != g_globalData->addressMap.end()) { RakNet::BitStream bsOutTest; bsOutTest.Write( (RakNet::MessageID)RH_SENDMAIL);//收公文提示消息 bsOutTest.Write( fromUser); bsOutTest.Write( toID[n]); bsOutTest.Write( title); bsOutTest.Write( content); bsOutTest.Write( 4); bsOutTest.Write( t); bsOutTest.Write( type); g_globalData->peer->Send( &bsOutTest, HIGH_PRIORITY, RELIABLE_ORDERED, 0, iter->second, false); printf("公文(2)下发\n"); } else{ printf("公文(2)未发送\n"); } } g_globalData->databaseLock.Unlock(); g_globalData->peer->DeallocatePacket( pIn); } else if(option == MAILNOTHROW)//审批未通过 { sprintf( sqlCmd, "UPDATE mail SET isread=3 where fromuser=%d and t=%d and todepartment=%d and type=%d", fromUser,t,toDepartment,type); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult(sqlCmd); g_globalData->databaseLock.Unlock(); g_globalData->peer->DeallocatePacket( pIn); //通知起草人: map<int, RakNet::SystemAddress>::iterator iter; iter = g_globalData->addressMap.find( fromUser); if( iter != g_globalData->addressMap.end()) { RakNet::BitStream bsOutTest; bsOutTest.Write( (RakNet::MessageID)RH_SENDMAIL);//收公文提示消息 bsOutTest.Write( fromUser); bsOutTest.Write( toDepartment); bsOutTest.Write( title); bsOutTest.Write( content); bsOutTest.Write( 3); bsOutTest.Write( t); bsOutTest.Write( type); g_globalData->peer->Send( &bsOutTest, HIGH_PRIORITY, RELIABLE_ORDERED, 0, iter->second, false); printf("%d公文(3)下发\n",fromUser); } else{ printf("%d公文(3)未发送\n",fromUser); } } else if(option == MAILSEND)//公文设置未读 { int toUser = toDepartment; printf("公文(4)\n"); sprintf( sqlCmd, "UPDATE mail SET isread=4 where fromuser=%d and t=%d and todepartment=%d and type=%d", fromUser,t,toDepartment,type); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult(sqlCmd); g_globalData->databaseLock.Unlock(); g_globalData->peer->DeallocatePacket( pIn); } else if(option == DONE)//公文已读 { int toUser = toDepartment; printf("公文(5)\n"); sprintf( sqlCmd, "UPDATE mail SET isread=5 where fromuser=%d and t=%d and todepartment=%d and type=%d", fromUser,t,toDepartment,type); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult(sqlCmd); g_globalData->databaseLock.Unlock(); g_globalData->peer->DeallocatePacket( pIn); } else if(option == PASSISREAD)//审批通过公文已读 { printf("公文(6)\n"); sprintf( sqlCmd, "UPDATE mail SET isread=6 where fromuser=%d and t=%d and todepartment=%d and type=%d", fromUser,t,toDepartment,type); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult(sqlCmd); g_globalData->databaseLock.Unlock(); g_globalData->peer->DeallocatePacket( pIn); } else if(option == NOTPASSISREAD)//未通过审批公文已读 { printf("公文(7)\n"); sprintf( sqlCmd, "UPDATE mail SET isread=7 where fromuser=%d and t=%d and todepartment=%d and type=%d", fromUser,t,toDepartment,type); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult(sqlCmd); g_globalData->databaseLock.Unlock(); g_globalData->peer->DeallocatePacket( pIn); } }
void PktManager::Manage(RakNet::Packet *packet, RakNet::RakPeerInterface *peer) { m_lastGameMessage = GetPacketIdentifier(packet); switch (m_lastGameMessage) { case ID_REMOTE_DISCONNECTION_NOTIFICATION: printf("Another client has disconnected.\n"); break; case ID_REMOTE_CONNECTION_LOST: printf("Another client has lost the connection.\n"); break; case ID_REMOTE_NEW_INCOMING_CONNECTION: printf("Another client has connected.\n"); mParent->AddClient(packet->systemAddress); break; case ID_NEW_INCOMING_CONNECTION: printf("A connection is incoming.\n"); mParent->AddClient(packet->systemAddress); break; case ID_NO_FREE_INCOMING_CONNECTIONS: printf("The server is full.\n"); break; case ID_DISCONNECTION_NOTIFICATION: printf("A client has disconnected.\n"); mParent->RemoveClient(packet->systemAddress); break; case ID_CONNECTION_LOST: printf("A client lost the connection.\n"); mParent->RemoveClient(packet->systemAddress); break; case ID_GAME_MESSAGE_1: { RakNet::RakString rs; //RakNet::Time timeStamp; RakNet::BitStream bsIn(packet->data,packet->length,false); ////Reading the timestamp //bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); //bsIn.Read(timeStamp); //printf("Messaggio inviato halle %i\n: ", timeStamp); //Reading the string bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(rs); printf("%s\n", rs.C_String()); } break; case ID_CLIENT_WANNA_PLAY: if(1)//tutti vogliono giocare { char positions []= {'n', 's', 'e', 'o'}; for(int i=0; i<mParent->GetPlayersNumber(); ++i) { printf("Sending ID_START_NEW_GAME to: %s \n", mParent->GetClientAddressAt(i).ToString()); RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_START_NEW_GAME); bsOut.Write(mParent->GetPlayersNumber()); bsOut.Write(positions[i]); //There are playersNumber-1 other players int index; for(int j=1; j<mParent->GetPlayersNumber(); ++j) { index = i+j; if(index > 3) index = 0; bsOut.Write(positions[index]); } peer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,mParent->GetClientAddressAt(i),false); } } break; default: printf("Message with identifier %i has arrived.\n", packet->data[0]); break; } }
bool Engine::Network::CNetworkEngine::Update() { if (m_bHost) { Engine::CActor* pcPlayer = m_pcWorld->GetActorByName("PlayerCube"); float fNewLocationX = pcPlayer->GetMetricMember("LocationX"); float fNewLocationY = pcPlayer->GetMetricMember("LocationY"); float fNewLocationZ = pcPlayer->GetMetricMember("LocationZ"); SendPosition(fNewLocationX, fNewLocationY, fNewLocationZ); float fNewRotationX = pcPlayer->GetMetricMember("RotationX"); float fNewRotationY = pcPlayer->GetMetricMember("RotationY"); float fNewRotationZ = pcPlayer->GetMetricMember("RotationZ"); SendRotation(fNewRotationX, fNewRotationY, fNewRotationZ); //Engine::CActor* pcScoreZone1 = m_pcWorld->GetActorByName("ScoreZone1"); //float fScore = pcScoreZone1->GetMetricMember("Score"); //SendScore(fScore); float fStamina = pcPlayer->GetMetricMember("Stamina"); SendStamina(fStamina); float fWalk = pcPlayer->GetMetricMember("SoundWalk"); float fSurface = pcPlayer->GetMetricMember("LastHitSurface"); SendSoundWalk(fWalk == 0.0f ? false : true, fSurface); float fSprint = pcPlayer->GetMetricMember("SoundSprint"); SendSoundSprint(fSprint == 0.0f ? false : true); } else { Engine::CActor* pcPlayer2 = m_pcWorld->GetActorByName("PlayerCube2"); float fNewLocationX = pcPlayer2->GetMetricMember("LocationX"); float fNewLocationY = pcPlayer2->GetMetricMember("LocationY"); float fNewLocationZ = pcPlayer2->GetMetricMember("LocationZ"); SendPosition(fNewLocationX, fNewLocationY, fNewLocationZ); float fNewRotationX = pcPlayer2->GetMetricMember("RotationX"); float fNewRotationY = pcPlayer2->GetMetricMember("RotationY"); float fNewRotationZ = pcPlayer2->GetMetricMember("RotationZ"); SendRotation(fNewRotationX, fNewRotationY, fNewRotationZ); //Engine::CActor* pcScoreZone2 = m_pcWorld->GetActorByName("ScoreZone2"); //float fScore = pcScoreZone2->GetMetricMember("Score"); //SendScore(fScore); float fStamina = pcPlayer2->GetMetricMember("Stamina"); SendStamina(fStamina); float fWalk = pcPlayer2->GetMetricMember("SoundWalk"); float fSurface = pcPlayer2->GetMetricMember("LastHitSurface"); SendSoundWalk(fWalk == 0.0f ? false : true, fSurface); float fSprint = pcPlayer2->GetMetricMember("SoundSprint"); SendSoundSprint(fSprint == 0.0f ? false : true); } for (m_pcPacket = m_pcPeer->Receive(); m_pcPacket; m_pcPeer->DeallocatePacket(m_pcPacket), m_pcPacket = m_pcPeer->Receive()) { switch (m_pcPacket->data[0]) { case ID_REMOTE_DISCONNECTION_NOTIFICATION: DEBUGPRINT("Another client has disconnected.\n"); m_bConnected = false; break; case ID_REMOTE_CONNECTION_LOST: DEBUGPRINT("Another client has lost the connection.\n"); break; case ID_REMOTE_NEW_INCOMING_CONNECTION: DEBUGPRINT("Another client has connected.\n"); m_bConnected = true; break; case ID_CONNECTION_REQUEST_ACCEPTED: { DEBUGPRINT("Our connection request has been accepted.\n"); m_bConnected = true; // Use a BitStream to write a custom user message // Bitstreams are easier to use than sending casted structures, and handle endian swapping automatically RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_GAME_VERSION); bsOut.Write(m_sztVersionNumber); m_pcPeer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, m_pcPacket->systemAddress, false); } break; case ID_NEW_INCOMING_CONNECTION: DEBUGPRINT("A connection is incoming.\n"); m_bConnected = true; break; case ID_NO_FREE_INCOMING_CONNECTIONS: DEBUGPRINT("The server is full.\n"); break; case ID_DISCONNECTION_NOTIFICATION: if (m_bHost) { DEBUGPRINT("A client has disconnected.\n"); } else { DEBUGPRINT("We have been disconnected.\n"); } m_bConnected = false; break; case ID_CONNECTION_LOST: if (m_bHost) { DEBUGPRINT("A client lost the connection.\n"); } else { DEBUGPRINT("Connection lost.\n"); } break; case ID_GAME_VERSION: { memcpy(m_pcSystemAddress, &(m_pcPacket->systemAddress), sizeof(RakNet::SystemAddress)); size_t sztVersion = 0; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(sztVersion); if (m_sztVersionNumber != sztVersion) { if (m_bHost) { DEBUGPRINT("Server is using version %i. Client had version %i. Disconnecting client.\n", m_sztVersionNumber, sztVersion); } else { DEBUGPRINT("Connected to server with matching version of %u\n", sztVersion); } m_pcPeer->CloseConnection(RakNet::AddressOrGUID(m_pcPacket), true); } else { if (m_bHost) { DEBUGPRINT("Client connected to server with matching version of %u\n", m_sztVersionNumber); RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_GAME_VERSION); bsOut.Write(m_sztVersionNumber); m_pcPeer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, m_pcPacket->systemAddress, false); } else { DEBUGPRINT("Connected to server with matching version %i.\n", m_sztVersionNumber); size_t sztNetworkID = 1; RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_GAME_SETUP); bsOut.Write(sztNetworkID); m_pcPeer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, m_pcPacket->systemAddress, false); } } } break; case ID_GAME_SETUP: { if (m_bHost) { Engine::CActor* pcPlayer = m_pcWorld->GetActorByName("PlayerCube"); Engine::CActor* pcPlayer2 = m_pcWorld->GetActorByName("PlayerCube2"); pcPlayer->SetDataMember("Status", "Enabled"); pcPlayer->SetDataMember("NetworkControl", "Enabled"); pcPlayer->SetMetricMember("LocationX", 0.0f); pcPlayer->SetMetricMember("LocationY", 0.0f); pcPlayer->SetMetricMember("LocationZ", -500.0f); pcPlayer->SetMetricMember("RotationX", 0.0f); pcPlayer->SetMetricMember("RotationY", 0.0f); pcPlayer->SetMetricMember("RotationZ", 0.0f); pcPlayer2->SetDataMember("Status", "Enabled"); pcPlayer2->SetDataMember("NetworkControl", "Disabled"); pcPlayer2->SetMetricMember("LocationX", 0.0f); pcPlayer2->SetMetricMember("LocationY", 0.0f); pcPlayer2->SetMetricMember("LocationZ", 500.0f); pcPlayer2->SetMetricMember("RotationX", 0.0f); pcPlayer2->SetMetricMember("RotationY", 180.0f); pcPlayer2->SetMetricMember("RotationZ", 0.0f); Engine::CActor* pcPlayer2Forward = m_pcWorld->GetActorByName("Player2Forward"); pcPlayer2Forward->SetDataMember("Status", "Enabled"); Engine::CActor* pcCamera = m_pcWorld->GetActorByName("Camera"); Engine::CActor* pcCamera2 = m_pcWorld->GetActorByName("Camera2"); pcCamera->SetDataMember("CameraStatus", "Enabled"); pcCamera2->SetDataMember("CameraStatus", "Disabled"); pcCamera->SetDataMember("LookAtStatus", "Enabled"); pcCamera2->SetDataMember("LookAtStatus", "Disabled"); Engine::CActor* pcScoreZone1 = m_pcWorld->GetActorByName("ScoreZone1"); Engine::CActor* pcScoreZone2 = m_pcWorld->GetActorByName("ScoreZone2"); pcScoreZone1->SetMetricMember("Score", 0.0f); pcScoreZone2->SetMetricMember("Score", 0.0f); pcScoreZone1->SetDataMember("TextStatus", "Enabled"); pcScoreZone2->SetDataMember("TextStatus", "Enabled"); size_t sztNetworkID = 2; RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_GAME_SETUP); bsOut.Write(sztNetworkID); m_pcPeer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, m_pcPacket->systemAddress, false); } else { Engine::CActor* pcPlayer = m_pcWorld->GetActorByName("PlayerCube"); Engine::CActor* pcPlayer2 = m_pcWorld->GetActorByName("PlayerCube2"); pcPlayer->SetDataMember("Status", "Enabled"); pcPlayer->SetDataMember("NetworkControl", "Disabled"); pcPlayer->SetMetricMember("LocationX", 0.0f); pcPlayer->SetMetricMember("LocationY", 0.0f); pcPlayer->SetMetricMember("LocationZ", -500.0f); pcPlayer->SetMetricMember("RotationX", 0.0f); pcPlayer->SetMetricMember("RotationY", 0.0f); pcPlayer->SetMetricMember("RotationZ", 0.0f); pcPlayer2->SetDataMember("Status", "Enabled"); pcPlayer2->SetDataMember("NetworkControl", "Enabled"); pcPlayer2->SetDataMember("Status", "Enabled"); pcPlayer2->SetMetricMember("LocationX", 0.0f); pcPlayer2->SetMetricMember("LocationY", 0.0f); pcPlayer2->SetMetricMember("LocationZ", 500.0f); pcPlayer2->SetMetricMember("RotationX", 0.0f); pcPlayer2->SetMetricMember("RotationY", 180.0f); pcPlayer2->SetMetricMember("RotationZ", 0.0f); pcPlayer2->SetInputMember("MovePositiveX", pcPlayer->GetInputMember("MovePositiveX")); pcPlayer2->SetInputMember("MovePositiveY", pcPlayer->GetInputMember("MovePositiveY")); pcPlayer2->SetInputMember("MovePositiveZ", pcPlayer->GetInputMember("MovePositiveZ")); pcPlayer2->SetInputMember("MoveNegativeX", pcPlayer->GetInputMember("MoveNegativeX")); pcPlayer2->SetInputMember("MoveNegativeY", pcPlayer->GetInputMember("MoveNegativeY")); pcPlayer2->SetInputMember("MoveNegativeZ", pcPlayer->GetInputMember("MoveNegativeZ")); pcPlayer2->SetInputMember("Run", pcPlayer->GetInputMember("Run")); Engine::CActor* pcCamera = m_pcWorld->GetActorByName("Camera"); Engine::CActor* pcCamera2 = m_pcWorld->GetActorByName("Camera2"); pcCamera->SetDataMember("CameraStatus", "Disabled"); pcCamera2->SetDataMember("CameraStatus", "Enabled"); pcCamera->SetDataMember("LookAtStatus", "Disabled"); pcCamera2->SetDataMember("LookAtStatus", "Enabled"); Engine::CActor* pcScoreZone1 = m_pcWorld->GetActorByName("ScoreZone1"); Engine::CActor* pcScoreZone2 = m_pcWorld->GetActorByName("ScoreZone2"); pcScoreZone1->SetMetricMember("Score", 0.0f); pcScoreZone2->SetMetricMember("Score", 0.0f); pcScoreZone1->SetDataMember("TextStatus", "Enabled"); pcScoreZone2->SetDataMember("TextStatus", "Enabled"); Engine::CActor* pcStaminaBar1 = m_pcWorld->GetActorByName("StaminaBar1"); pcStaminaBar1->SetDataMember("ActiveState", "Game"); Engine::CActor* pcStaminaBar2 = m_pcWorld->GetActorByName("StaminaBar2"); pcStaminaBar2->SetDataMember("ActiveState", "Game"); Engine::CActor* pcPlayer2Forward = m_pcWorld->GetActorByName("Player2Forward"); pcPlayer2Forward->SetDataMember("Status", "Enabled"); } } break; case ID_GAME_POSITION: { if (m_bHost) { float fX = 0.0f; float fY = 0.0f; float fZ = 0.0f; float fLastHit = 0.0f; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(fX); bsIn.Read(fY); bsIn.Read(fZ); Engine::CActor* pcPlayer2 = m_pcWorld->GetActorByName("PlayerCube2"); pcPlayer2->SetMetricMember("LocationX", fX); pcPlayer2->SetMetricMember("LocationY", fY); pcPlayer2->SetMetricMember("LocationZ", fZ); m_pcWorld->ResetTimer(); } else { float fX = 0.0f; float fY = 0.0f; float fZ = 0.0f; float fPlaySound = -1.0f; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(fX); bsIn.Read(fY); bsIn.Read(fZ); Engine::CActor* pcPlayer = m_pcWorld->GetActorByName("PlayerCube"); pcPlayer->SetMetricMember("LocationX", fX); pcPlayer->SetMetricMember("LocationY", fY); pcPlayer->SetMetricMember("LocationZ", fZ); m_pcWorld->ResetTimer(); } } break; case ID_GAME_ROTATION: { if (m_bHost) { float fX = 0.0f; float fY = 0.0f; float fZ = 0.0f; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(fX); bsIn.Read(fY); bsIn.Read(fZ); Engine::CActor* pcPlayer2 = m_pcWorld->GetActorByName("PlayerCube2"); pcPlayer2->SetMetricMember("RotationX", fX); pcPlayer2->SetMetricMember("RotationY", fY); pcPlayer2->SetMetricMember("RotationZ", fZ); m_pcWorld->ResetTimer(); } else { float fX = 0.0f; float fY = 0.0f; float fZ = 0.0f; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(fX); bsIn.Read(fY); bsIn.Read(fZ); Engine::CActor* pcPlayer = m_pcWorld->GetActorByName("PlayerCube"); pcPlayer->SetMetricMember("RotationX", fX); pcPlayer->SetMetricMember("RotationY", fY); pcPlayer->SetMetricMember("RotationZ", fZ); m_pcWorld->ResetTimer(); } } break; case ID_GAME_SCORE: { if (m_bHost) { float fScore = 0.0f; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(fScore); Engine::CActor* pcScoreZone2 = m_pcWorld->GetActorByName("ScoreZone2"); pcScoreZone2->SetMetricMember("Score", fScore); m_pcWorld->ResetTimer(); } else { float fScore = 0.0f; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(fScore); Engine::CActor* pcScoreZone1 = m_pcWorld->GetActorByName("ScoreZone1"); pcScoreZone1->SetMetricMember("Score", fScore); m_pcWorld->ResetTimer(); } } break; case ID_GAME_STAMINA: { if (m_bHost) { float fStamina = 0.0f; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(fStamina); Engine::CActor* pcPlayer2 = m_pcWorld->GetActorByName("PlayerCube2"); pcPlayer2->SetMetricMember("Stamina", fStamina); m_pcWorld->ResetTimer(); } else { float fStamina = 0.0f; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(fStamina); Engine::CActor* pcPlayer = m_pcWorld->GetActorByName("PlayerCube"); pcPlayer->SetMetricMember("Stamina", fStamina); m_pcWorld->ResetTimer(); } } break; case ID_SOUND_SPRINT: { bool bSprint = false; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(bSprint); if (bSprint) { if (eae6320::UserSettings::IsSoundOn()) { Engine::CActor* pcPlayer = nullptr; if (m_bHost) { pcPlayer = m_pcWorld->GetActorByName("PlayerCube2"); } else { pcPlayer = m_pcWorld->GetActorByName("PlayerCube"); } float fX = pcPlayer->GetMetricMember("LocationX"); float fY = pcPlayer->GetMetricMember("LocationY"); float fZ = pcPlayer->GetMetricMember("LocationZ"); Shared::Math::CVector3 v3Position(fX, fY, fZ); Shared::Math::CVector3 v3Velocity(0.0f, 0.0f, 0.0f); m_pcSoundEngine->Play3D(m_pcSprintSound, m_pcSprintChannel, v3Position, v3Velocity); m_pcSoundEngine->SetVolume(50.0f * eae6320::UserSettings::GetSoundVolumeLevel(), m_pcSprintChannel); } } else { m_pcSoundEngine->Stop(m_pcSprintChannel); } m_pcWorld->ResetTimer(); } break; case ID_SOUND_WALK: { float fSurface = -1.0f; bool bWalk = false; RakNet::BitStream bsIn(m_pcPacket->data, m_pcPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(bWalk); bsIn.Read(fSurface); if (bWalk) { Engine::CActor* pcPlayer = nullptr; if (m_bHost) { pcPlayer = m_pcWorld->GetActorByName("PlayerCube2"); } else { pcPlayer = m_pcWorld->GetActorByName("PlayerCube"); } float fX = pcPlayer->GetMetricMember("LocationX"); float fY = pcPlayer->GetMetricMember("LocationY"); float fZ = pcPlayer->GetMetricMember("LocationZ"); Shared::Math::CVector3 v3Position(fX, fY, fZ); Shared::Math::CVector3 v3Velocity(0.0f, 0.0f, 0.0f); switch (static_cast<int>(fSurface)) { case 0: if (eae6320::UserSettings::IsSoundOn()) { m_pcSoundEngine->Play3D(m_pcGroundSound, m_pcGroundChannel, v3Position, v3Velocity); m_pcSoundEngine->SetVolume(1.0f * eae6320::UserSettings::GetSoundVolumeLevel(), m_pcGroundChannel); } m_pcSoundEngine->Stop(m_pcStairChannel); break; case 1: if (eae6320::UserSettings::IsSoundOn()) { m_pcSoundEngine->Play3D(m_pcStairSound, m_pcStairChannel, v3Position, v3Velocity); m_pcSoundEngine->SetVolume(1.0f * eae6320::UserSettings::GetSoundVolumeLevel(), m_pcStairChannel); } m_pcSoundEngine->Stop(m_pcGroundChannel); break; default: m_pcSoundEngine->Stop(m_pcGroundChannel); m_pcSoundEngine->Stop(m_pcStairChannel); break; } } else { m_pcSoundEngine->Stop(m_pcGroundChannel); m_pcSoundEngine->Stop(m_pcStairChannel); } m_pcWorld->ResetTimer(); } break; default: DEBUGPRINT("Message with identifier %i has arrived.\n", m_pcPacket->data[0]); break; } } return true; }
void BaseConnection::Update(Packet* packet, RakPeerInterface* peer) { switch (packet->data[0]) { case ID_REMOTE_DISCONNECTION_NOTIFICATION: { printf("A client has disconnected.\n"); break; } case ID_REMOTE_CONNECTION_LOST: { printf("A client has lost the connection 1.\n"); BitStream bsIn(packet->data, packet->length, false); Player* player = mCurrentPlayers.GetPlayer(packet->guid); player->Save(); mCurrentPlayers.Disconnect(packet->guid); --mActiveConnections; break; } case ID_REMOTE_NEW_INCOMING_CONNECTION: { printf("A client has connected.\n"); ++mActiveConnections; break; } case ID_CONNECTION_REQUEST_ACCEPTED: { printf("Our connection request has been accepted.\n"); ++mActiveConnections; break; } case ID_NEW_INCOMING_CONNECTION: { printf("A connection is incoming.\n"); ++mActiveConnections; break; } case ID_NO_FREE_INCOMING_CONNECTIONS: { printf("The server is full.\n"); break; } case ID_DISCONNECTION_NOTIFICATION: { printf("A client has disconnected.\n"); BitStream bsIn(packet->data, packet->length, false); Player* player = mCurrentPlayers.GetPlayer(packet->guid); player->Save(); mCurrentPlayers.Disconnect(packet->guid); --mActiveConnections; break; } case ID_CONNECTION_LOST: { printf("A client lost the connection. 2\n"); BitStream bsIn(packet->data, packet->length, false); Player* player = mCurrentPlayers.GetPlayer(packet->guid); player->Save(); mCurrentPlayers.Disconnect(packet->guid); --mActiveConnections; break; } } char temp[CHAR_MAX]; sprintf(temp, "Eclipse++ Server - Active Connections: %d", mActiveConnections); // TODO make magic //SetConsoleTitleA(temp); }
void GamePlay::UpdateRaknet(Packet* packet, RakPeerInterface* peer) { if(!mInit) { return; } mChat.Update(packet, peer); mPlayerPosition.UpdateRaknet(packet, peer); mActiveMaps.UpdateRaknet(packet, peer); mCommands.UpdateRaknet(packet, peer); mItemEqiups.UpdateRaknet(packet, peer); mNPC.UpdateRaknet(packet, peer); switch (packet->data[0]) { case ID_GET_PLAYER_INFO: { BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); Player* player = mCurrentPlayers.GetPlayer(packet->guid); // Send them the player RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_GET_PLAYER_INFO); bsOut.Write( *player ); peer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0, packet->guid, false); printf("Player info requested with GUID: %s\n", packet->guid.ToString()); // Let everyone else know that we joined :) mPlayerPosition.NewPlayer(player->GetMap(), (*player) ,packet, peer); break; } case ID_GET_ITEMS: { // Send the player the items he has in his inventory mCurrentPlayers.GetPlayer(packet->guid)->GetItems(packet, peer); break; } case ID_MAP_DATA: { MapData* mapData = NULL; BitStream bsIn(packet->data, packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); int map = mCurrentPlayers.GetPlayer(packet->guid)->GetMap(); if(!mActiveMaps.DoesMapExist(map)) { mapData = new MapData;; MapLoad mapLoad(*mapData, mActiveMaps); mapLoad.Load(map); } else { mapData = mActiveMaps.GetMap(map); } mapData->AddPlayer(packet->guid); // Send them the map RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_MAP_DATA); bsOut.Write( map ); bsOut.Write( mapData->GetWidth() ); bsOut.Write( mapData->GetHeight() ); bsOut.Write( mapData->GetTileAmount() ); mapData->SendInfo(bsOut, packet); peer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0, packet->guid, false); break; } case ID_GET_ACTIVE_PLAYERS: { BitStream bsIn(packet->data, packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); int map = 0; bsIn.Read(map); list<Player>& players = mCurrentPlayers.GetList(); // Send the client all the active players on the same map as them for(list<Player>::iterator iter = players.begin(); iter != players.end(); ++iter) { // Dont send our own info back to ourselves if(iter->GetGUID() == packet->guid) { continue; } // If player is on the same map if(iter->GetMap() == map) { // Send that player the position info RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_GET_PLAYER); bsOut.Write(*iter); peer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet->guid,false); } } break; } case ID_REMOVE_ITEM: { printf("Player Used Item\n"); BitStream bsIn(packet->data, packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); int itemNumber = 0; bsIn.Read(itemNumber); mCurrentPlayers.GetPlayer(packet->guid)->RemoveItem(itemNumber); break; } case ID_ADD_HEALTH: { BitStream bsIn(packet->data, packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); int health = 0; bsIn.Read(health); mCurrentPlayers.GetPlayer(packet->guid)->AddHealth(health); break; } case ID_ADD_MANA: { BitStream bsIn(packet->data, packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); int mana = 0; bsIn.Read(mana); mCurrentPlayers.GetPlayer(packet->guid)->AddMana(mana); break; } } }
int main(int argc, char **argv) { const char *DEFAULT_SERVER_ADDRESS="test.dnsalias.net"; const unsigned short DEFAULT_SERVER_PORT=60000; const char *serverAddress; unsigned short serverPort; #ifndef _DEBUG // Only use DEFAULT_SERVER_ADDRESS for debugging if (argc<2) { PrintHelp(); return false; } #endif if (argc<2) serverAddress=DEFAULT_SERVER_ADDRESS; else serverAddress=argv[1]; if (argc<3) serverPort=DEFAULT_SERVER_PORT; else serverPort=atoi(argv[2]); // ---- RAKPEER ----- RakNet::RakPeerInterface *rakPeer; rakPeer=RakNet::RakPeerInterface::GetInstance(); static const unsigned short clientLocalPort=0; RakNet::SocketDescriptor sd(clientLocalPort,0); // Change this if you want RakNet::StartupResult sr = rakPeer->Startup(1,&sd,1); // Change this if you want rakPeer->SetMaximumIncomingConnections(0); // Change this if you want if (sr!=RakNet::RAKNET_STARTED) { printf("Startup failed. Reason=%i\n", (int) sr); return 1; } RakNet::CloudClient cloudClient; rakPeer->AttachPlugin(&cloudClient); RakNet::ConnectionAttemptResult car = rakPeer->Connect(serverAddress, serverPort, 0, 0); if (car==RakNet::CANNOT_RESOLVE_DOMAIN_NAME) { printf("Cannot resolve domain name\n"); return 1; } printf("Connecting to %s...\n", serverAddress); bool didRebalance=false; // So we only reconnect to a lower load server once, for load balancing RakNet::Packet *packet; while (1) { for (packet=rakPeer->Receive(); packet; rakPeer->DeallocatePacket(packet), packet=rakPeer->Receive()) { switch (packet->data[0]) { case ID_CONNECTION_LOST: printf("Lost connection to server.\n"); return 1; case ID_CONNECTION_ATTEMPT_FAILED: printf("Failed to connect to server at %s.\n", packet->systemAddress.ToString(true)); return 1; case ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY: case ID_OUR_SYSTEM_REQUIRES_SECURITY: case ID_PUBLIC_KEY_MISMATCH: case ID_INVALID_PASSWORD: case ID_CONNECTION_BANNED: // You won't see these unless you modified CloudServer printf("Server rejected the connection.\n"); return 1; case ID_INCOMPATIBLE_PROTOCOL_VERSION: printf("Server is running an incompatible RakNet version.\n"); return 1; case ID_NO_FREE_INCOMING_CONNECTIONS: printf("Server has no free connections\n"); return 1; case ID_IP_RECENTLY_CONNECTED: printf("Recently connected. Retrying."); rakPeer->Connect(serverAddress, serverPort, 0, 0); break; case ID_CONNECTION_REQUEST_ACCEPTED: printf("Connected to server.\n"); UploadInstanceToCloud(&cloudClient, packet->guid); GetClientSubscription(&cloudClient, packet->guid); GetServers(&cloudClient, packet->guid); break; case ID_CLOUD_GET_RESPONSE: { RakNet::CloudQueryResult cloudQueryResult; cloudClient.OnGetReponse(&cloudQueryResult, packet); unsigned int rowIndex; const bool wasCallToGetServers=cloudQueryResult.cloudQuery.keys[0].primaryKey=="CloudConnCount"; printf("\n"); if (wasCallToGetServers) printf("Downloaded server list. %i servers.\n", cloudQueryResult.rowsReturned.Size()); else printf("Downloaded client list. %i clients.\n", cloudQueryResult.rowsReturned.Size()); unsigned short connectionsOnOurServer=65535; unsigned short lowestConnectionsServer=65535; RakNet::SystemAddress lowestConnectionAddress; for (rowIndex=0; rowIndex < cloudQueryResult.rowsReturned.Size(); rowIndex++) { RakNet::CloudQueryRow *row = cloudQueryResult.rowsReturned[rowIndex]; if (wasCallToGetServers) { unsigned short connCount; RakNet::BitStream bsIn(row->data, row->length, false); bsIn.Read(connCount); printf("%i. Server found at %s with %i connections\n", rowIndex+1, row->serverSystemAddress.ToString(true), connCount); unsigned short connectionsExcludingOurselves; if (row->serverGUID==packet->guid) connectionsExcludingOurselves=connCount-1; else connectionsExcludingOurselves=connCount; // Find the lowest load server (optional) if (packet->guid==row->serverGUID) { connectionsOnOurServer=connectionsExcludingOurselves; } else if (connectionsExcludingOurselves < lowestConnectionsServer) { lowestConnectionsServer=connectionsExcludingOurselves; lowestConnectionAddress=row->serverSystemAddress; } } else { printf("%i. Client found at %s", rowIndex+1, row->clientSystemAddress.ToString(true)); if (row->clientGUID==rakPeer->GetMyGUID()) printf(" (Ourselves)"); RakNet::BitStream bsIn(row->data, row->length, false); RakNet::RakString clientData; bsIn.Read(clientData); printf(" Data: %s", clientData.C_String()); printf("\n"); } } // Do load balancing by reconnecting to lowest load server (optional) if (didRebalance==false && wasCallToGetServers && cloudQueryResult.rowsReturned.Size()>0 && connectionsOnOurServer>lowestConnectionsServer) { printf("Reconnecting to lower load server %s\n", lowestConnectionAddress.ToString(false)); rakPeer->CloseConnection(packet->guid, true); // Wait for the thread to close, otherwise will immediately get back ID_CONNECTION_ATTEMPT_FAILED because no free outgoing connection slots // Alternatively, just call Startup() with 2 slots instead of 1 RakSleep(500); rakPeer->Connect(lowestConnectionAddress.ToString(false), lowestConnectionAddress.GetPort(), 0, 0); didRebalance=true; } cloudClient.DeallocateWithDefaultAllocator(&cloudQueryResult); } break; case ID_CLOUD_SUBSCRIPTION_NOTIFICATION: { bool wasUpdated; RakNet::CloudQueryRow cloudQueryRow; cloudClient.OnSubscriptionNotification(&wasUpdated, &cloudQueryRow, packet, 0 ); if (wasUpdated) printf("New client at %s\n", cloudQueryRow.clientSystemAddress.ToString(true)); else printf("Lost client at %s\n", cloudQueryRow.clientSystemAddress.ToString(true)); cloudClient.DeallocateWithDefaultAllocator(&cloudQueryRow); } break; } } // Any additional client processing can go here RakSleep(30); } RakNet::RakPeerInterface::DestroyInstance(rakPeer); return 0; }
int _tmain(int argc, _TCHAR* argv[]) { // Create networking interfaces RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance(); RakNet::Packet *packet; // Initialize a socket descriptor RakNet::SocketDescriptor sd( 5187, 0 ); // Start a server with max. 5 clients peer->Startup( 5, &sd, 1 ); printf( "Starting the server...\n" ); // Set the maximum number of clients peer->SetMaximumIncomingConnections( 5 ); // Listen printf( "Listening...\n" ); while( 1 ) { for( packet = peer->Receive(); packet; peer->DeallocatePacket( packet ), packet = peer->Receive() ) { switch( packet->data[0] ) { case ID_NEW_INCOMING_CONNECTION: printf("A connection is incoming.\n"); break; case ID_NO_FREE_INCOMING_CONNECTIONS: printf("The server is full.\n"); break; case ID_DISCONNECTION_NOTIFICATION: printf("A client has disconnected.\n"); break; case ID_CONNECTION_LOST: printf("A client lost the connection.\n"); break; case ID_SC4_CONNECTION_DATA: { printf( "An SC4Multi connection was made:\n" ); // Create several RakNet strings for reading the bistream RakNet::RakString username, guid, city; // Read the packet into the bitstream RakNet::BitStream bsIn(packet->data,packet->length,false); // Ignore the packet ID, which we already know bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); // Read the bitstream into our variables bsIn.Read( username ); bsIn.Read( guid ); bsIn.Read( city ); // Print the data printf ( "\tUsername | %s\n" "\tGUID | %s\n" "\tCity | %s\n", username.C_String(), guid.C_String(), city.C_String() ); break; } default: printf("Message with identifier %i has arrived.\n", packet->data[0]); break; } } } // Shut down RakNet::RakPeerInterface::DestroyInstance( peer ); return 0; }
void Inventory::UpdateRaknet() { switch (mRaknet.mPacket->data[0]) { case ID_PICKUP_ITEM: { ItemBase* item; int itemType = 0; char itemName[CHAR_MAX]; int value = 0; bool questItem = 0; int imageNumber = 0; char description[1000]; int itemNumber = 0; RakNet::BitStream bsIn(mRaknet.mPacket->data, mRaknet.mPacket->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(itemType); bsIn.Read(itemName); bsIn.Read(value); bsIn.Read(questItem); bsIn.Read(imageNumber); bsIn.Read(description); bsIn.Read(itemNumber); switch (itemType) { case potion: { item = new Potion; break; } case weapon: { item = new Weapon; break; } case shield: { item = new Shield; break; } case helmet: { item = new Helmet; break; } case armor: { item = new Armor; break; } case boots: { item = new Boots; break; } case necklace: { item = new Necklace; break; } case ring: { item = new Ring; break; } } SetValues(item, itemName, value, questItem, imageNumber, description, itemNumber); item->GetData(bsIn); AddItem(item); break; } } }
void NetworkEngine::createSkill(RakNet::Packet * packet) { RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); //En otros sitios esta como bsIn.IgnoreBytes(1), es lo mismo unsigned int name; Vector2d pos; Vector2d posPlayer; RakNet::NetworkID id; bsIn.Read(name); bsIn.Read(pos); bsIn.Read(posPlayer); bsIn.Read(id); GameObject* start = NULL; GameObject* end = NULL; Message message; switch (name) { case GameObject::N_BUILDING_MINE: GameManager::getInstance()->getGameObjectManager()->createBuildingMine(pos); break; case GameObject::N_MINE2: GameManager::getInstance()->getGameObjectManager()->createBuildingMine2(pos); break; case GameObject::N_MINE3: GameManager::getInstance()->getGameObjectManager()->createBuildingMine3(pos); break; case GameObject::N_BUILDING_TURRET_BULLET: GameManager::getInstance()->getGameObjectManager()->createBuildingTurret2(pos); break; case GameObject::N_BUILDING_TURRET_PROJECTILE: GameManager::getInstance()->getGameObjectManager()->createBuildingTurret(pos); break; case GameObject::N_BUILDING_TURRET_2_CANON: GameManager::getInstance()->getGameObjectManager()->createBuildingTurret2Canon(pos); break; case GameObject::N_BUILDING_TURRET_1_CANON: GameManager::getInstance()->getGameObjectManager()->createBuildingTurret1Canon(pos); break; case GameObject::N_BUILDING_TURRET_BIG_CANON: GameManager::getInstance()->getGameObjectManager()->createBuildingTurretBigCanon(pos); break; case GameObject::N_BUILDING_WALL: start = GameManager::getInstance()->getGameObjectManager()->createBuildingWall(pos); start->rotation = (posPlayer-pos).getAngle(); end = GameManager::getInstance()->getGameObjectManager()->createBuildingWall(posPlayer); end->rotation = (pos-posPlayer).getAngle(); GameManager::getInstance()->getGameObjectManager()->createBuildingEnergyWall(start,end); break; case GameObject::N_SKILL_MULTIPLE_SHOT: GameManager::getInstance()->getGameObjectManager()->createSkillMultimpleShot(posPlayer); break; case GameObject::N_SKILL_BOMB: GameManager::getInstance()->getGameObjectManager()->createSkillBomb(pos); break; case GameObject::N_SKILL_HEAL: GameManager::getInstance()->getGameObjectManager()->createSkillHeal(pos); break; case GameObject::N_SKILL_TARGET_PROJECTILE: message.type = Message::NEW_TARGET; message.gameObject = replicaManager->getGameObjectByNetworkID(id); GameObject* projectile; projectile = GameManager::getInstance()->getGameObjectManager()->createTargetProjectile(0); if(message.gameObject == NULL) { message.target = posPlayer + (pos-posPlayer)*5000;; } projectile->rotation = (pos - posPlayer).getAngle(); projectile->position = posPlayer + Vector2d::getVector2dByAngle(-projectile->rotation)*7; projectile->velocity = (pos - posPlayer).normalize(); projectile->broadcastMessage(message); break; case GameObject::N_SKILL_TARGET_HEAL: start = replicaManager->getGameObjectByNetworkID(id); if(start != NULL) { message.type = Message::INCOMING_DAMAGE; message.value = -100; start->broadcastMessage(message); } break; } }
void MainGameScene::update(float dt) { // update game scene //update character mainCharacter->Update(dt); // update blocks //iterate through the list std::list<ColorBlock*>::iterator it; //lets just pretend that no more than 5 blocks will be deleted in the same frame std::list<ColorBlock*>::iterator toDelete[5]; int amountToDelete = 0; for (it = blocksList.begin(); it != blocksList.end(); it++) { // only process if the block isn't dying if (!(*it)->GetDying()) { // check if it's time to kill the block if ((*it)->getPositionY() > 650.0f || (*it)->getPositionY() < -85.0f || (*it)->getPositionX() < -20.0f || (*it)->getPositionX() > 850.0f) { if(amountToDelete < 5) { toDelete[amountToDelete] = it; amountToDelete++; } } else { // dont process if the block is already connected with the character if (!(*it)->GetAttached()) { // process colision detection b2ContactEdge* edge = (*it)->GetBody()->GetContactList(); while (edge != NULL) // if == null, no more collisions { if (edge->contact->IsTouching()) { // iterate through the list of contacts // if collided with character, don't delete if (((CCSprite*)edge->contact->GetFixtureB()->GetBody()->GetUserData())->getTag() == CHARACTER_TAG || ((CCSprite*)edge->contact->GetFixtureA()->GetBody()->GetUserData())->getTag() == CHARACTER_TAG) { // the block collided with character (*it)->AttachTo(mainCharacter->GetBody()); } // check if it's a attached block, so attached to this one else if (((CCSprite*)edge->contact->GetFixtureB()->GetBody()->GetUserData())->getTag() == BLOCK_TAG && ((CCSprite*)edge->contact->GetFixtureA()->GetBody()->GetUserData())->getTag() == BLOCK_TAG) { // check which one is the IT // attached based on this if (edge->contact->GetFixtureA()->GetBody() == (*it)->GetBody()) { // make sure it's already attached if(((ColorBlock*)edge->contact->GetFixtureB()->GetBody()->GetUserData())->GetAttached() && !((ColorBlock*)edge->contact->GetFixtureB()->GetBody()->GetUserData())->GetDying()) { // attach on B fixture (*it)->AttachTo(edge->contact->GetFixtureB()->GetBody()); } } else { if(((ColorBlock*)edge->contact->GetFixtureA()->GetBody()->GetUserData())->GetAttached() && !((ColorBlock*)edge->contact->GetFixtureA()->GetBody()->GetUserData())->GetDying()) { // attach on A fixture (*it)->AttachTo(edge->contact->GetFixtureA()->GetBody()); } } } } edge = edge->next; // go to the next colision } } // now process those which are already attached to the character body else { (*it)->BuildConnections(NULL, -1); // check if one of the attached blocks is on the death area if ((*it)->getPositionX() < 0.0f || (*it)->getPositionX() > 800.0f || (*it)->getPositionY() > 600.0f || (*it)->getPositionY() < 0.0f) { if (isConnected) { //send gameover signal through network RakNet::BitStream BsOut; BsOut.Write((RakNet::MessageID)ID_GAME_PLAYER_LOST); player2->Send(&BsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,player2Adress,false); } // game over animation goes here // for now just call the next scene //CCDirector::sharedDirector()->replaceScene(CCTransitionProgressHorizontal::transitionWithDuration(1.0f,PointsScene::scene())); CCDirector::sharedDirector()->pushScene(CCTransitionProgressHorizontal::transitionWithDuration(1.0f,PointsScene::scene())); // to prevent thousands of scenes being created this->unscheduleUpdate(); } } } } else { // check if it's time to be deleted if((*it)->getOpacity() == 0) { if(amountToDelete < 5) { toDelete[amountToDelete] = it; amountToDelete++; } } } } // delete dead ones for (int i = 0; i < amountToDelete; i++) { // remove from batch blocksBatch->removeChild((*toDelete[i]),true); // remove from local list blocksList.erase(toDelete[i]); } // update physics engine box2DWorld->Step(dt,20,20); // update raknet if (isConnected) { // receive packets RakNet::Packet* packet; for (packet = player2->Receive();packet;player2->DeallocatePacket(packet),packet=player2->Receive()) { // only process a packet that came from the other player if (packet->systemAddress == player2Adress) { // player disconnected if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { isConnected = false; // put some warning on the screen //create a text and make it goes up CCLabelBMFont* discWarning = CCLabelBMFont::create("Your opponent just disconnected","Assets/badab.fnt"); discWarning->setColor(ccc3(255,0,0)); discWarning->setPosition(ccp(400.0f,-20.0f)); CCSequence* warningSequence = CCSequence::create(CCMoveTo::create(4.0f,ccp(400.0f,200.0f)), CCCallFuncO::create(this,callfuncO_selector(MainGameScene::DeleteDisctionnectionWarning),discWarning)); discWarning->runAction(warningSequence); discWarning->runAction(CCFadeOut::create(4.0f));//fade this->addChild(discWarning,1000); } // other player just lost else if (packet->data[0] == ID_GAME_PLAYER_LOST) { otherGameOver = true; } else if (packet->data[0] == ID_GAME_NEW_POINTS) { // read new points from the other player int rs = 0; RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read((char*)&rs,sizeof(int)); pointsManager->SetP2Points(rs); } else if(packet->data[0] == ID_GAME_INIT_SWAP) { // other player will swap, prepare ChangeScreenSpecial* change = ChangeScreenSpecial::create(); this->addChild(change,701); change->ExecuteActual(); change->setTag(978); } else if(packet->data[0] == ID_GAME_SWAP_SCREENS) { // received information std::vector<BlockInformation> received; RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); // number of blocks within the package int size = 0; bsIn.Read((char*)&size,sizeof(int)); BlockInformation* reci = new BlockInformation[size]; bsIn.Read((char*)reci,sizeof(BlockInformation) * size); // put on the received vector for (int p = 0; p < size; p++) { received.push_back(reci[p]); } delete reci; // now change the blocks //delete all non-dying blocks std::list<ColorBlock*>::iterator it; std::vector<ColorBlock*> toDelete; for (it = blocksList.begin(); it != blocksList.end(); it++) { if (!(*it)->GetDying()) { toDelete.push_back(*it); } } //delete them for (int c = 0; c < toDelete.size();c++) { blocksBatch->removeChild(toDelete[c],true); blocksList.remove(toDelete[c]); } //put them back for (int c = 0; c < received.size(); c++) { // create block on a random location ColorBlock* newBlock = ColorBlock::create("Assets/block.png"); // unattached blocks have 50% opacity newBlock->setOpacity(127); newBlock->setPositionX(received[c].posX); newBlock->setPositionY(received[c].posY); // add as a child to the batch blocksBatch->addChild(newBlock); //mainScene->addChild(newBlock); newBlock->InitInWorld(box2DWorld); if (received[c].color == BLOCK_GREEN) { newBlock->setColor(ccc3(0,255,0)); } else if (received[c].color == BLOCK_RED) { newBlock->setColor(ccc3(255,0,0)); } else if (received[c].color == BLOCK_BLUE) { newBlock->setColor(ccc3(0,0,255)); } // add to local list blocksList.push_back(newBlock); } } } } } }
void WINAPI OnSetDepartment(PTP_CALLBACK_INSTANCE pInstance, void* packet) { RakNet::Packet* pIn = (RakNet::Packet*)packet; RakNet::BitStream bsIn( pIn->data, pIn->length, false); bsIn.IgnoreBytes( sizeof(RakNet::MessageID)); int setDepartmentOption; bsIn.Read( setDepartmentOption); if( setDepartmentOption == SDO_NEW) { RakNet::RakString name; bsIn.Read( name); char sqlCmd[128]; sprintf( sqlCmd, "INSERT INTO department SET department_name='%s'", name.C_String()); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult(sqlCmd); g_globalData->databaseLock.Unlock(); g_globalData->databaseLock.Lock(); sprintf( sqlCmd, "SELECT id FROM department WHERE department_name='%s'", name.C_String()); g_globalData->database->QueryWithResult(sqlCmd); g_globalData->database->FetchRow(); int departmentID = g_globalData->database->GetResultInt(0); g_globalData->database->FreeResult(); g_globalData->databaseLock.Unlock(); RakNet::BitStream bsOut; bsOut.Write( (RakNet::MessageID)RH_SET_DEPARTMENT); bsOut.Write( SDO_NEW); bsOut.Write( departmentID); bsOut.Write( name); g_globalData->peer->Send( &bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, pIn->systemAddress, false); g_globalData->peer->Send( &bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, pIn->systemAddress, true); } else if( setDepartmentOption == SDO_DELETE) { int ID; bsIn.Read(ID); char sqlCmd[128]; sprintf( sqlCmd, "DELETE FROM account WHERE department=%d", ID); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult( sqlCmd); g_globalData->databaseLock.Unlock(); sprintf( sqlCmd, "DELETE FROM department WHERE id=%d", ID); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult( sqlCmd); g_globalData->databaseLock.Unlock(); RakNet::BitStream bsOut; bsOut.Write( (RakNet::MessageID)RH_SET_DEPARTMENT); bsOut.Write( SDO_DELETE); bsOut.Write( ID); g_globalData->peer->Send( &bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, pIn->systemAddress, false); g_globalData->peer->Send( &bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, pIn->systemAddress, true); } else if( setDepartmentOption == SDO_SET_MASTER) { int departmentID, humanID; char sqlCmd[128]; bsIn.Read( departmentID); bsIn.Read( humanID); sprintf( sqlCmd, "UPDATE account SET priority=1 WHERE department=%d AND priority=2", departmentID); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult( sqlCmd); g_globalData->databaseLock.Unlock(); sprintf( sqlCmd, "UPDATE account SET priority=2 WHERE Id=%d AND priority=1", humanID); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult( sqlCmd); g_globalData->databaseLock.Unlock(); sprintf( sqlCmd, "UPDATE department SET department_master=%d WHERE Id=%d", humanID, departmentID); g_globalData->databaseLock.Lock(); g_globalData->database->QueryWithoutResult( sqlCmd); g_globalData->databaseLock.Unlock(); RakNet::BitStream bsOut; bsOut.Write( (RakNet::MessageID)RH_SET_DEPARTMENT); bsOut.Write( SDO_SET_MASTER); bsOut.Write( departmentID); bsOut.Write( humanID); g_globalData->peer->Send( &bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, pIn->systemAddress, false); g_globalData->peer->Send( &bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, pIn->systemAddress, true); } g_globalData->peer->DeallocatePacket( pIn); }
void FullyConnectedMesh2::OnRequestFCMGuid(Packet *packet) { RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(MessageID)); bool hasRemoteFCMGuid; bsIn.Read(hasRemoteFCMGuid); RakNetTimeUS senderElapsedRuntime=0; unsigned int remoteTotalConnectionCount=0; FCM2Guid theirFCMGuid=0; if (hasRemoteFCMGuid) { bsIn.Read(remoteTotalConnectionCount); bsIn.Read(theirFCMGuid); } else { bsIn.Read(senderElapsedRuntime); } AddParticipantInternal(packet->guid,theirFCMGuid); if (ourFCMGuid==0) { if (hasRemoteFCMGuid==false) { // Nobody has a fcmGuid RakNetTimeUS ourElapsedRuntime = GetElapsedRuntime(); if (ourElapsedRuntime>senderElapsedRuntime) { // We are probably host SendConnectionCountResponse(packet->systemAddress, 2); } else { // They are probably host SendConnectionCountResponse(packet->systemAddress, 1); } } else { // They have a fcmGuid, we do not IncrementTotalConnectionCount(remoteTotalConnectionCount+1); AssignOurFCMGuid(); DataStructures::DefaultIndexType idx; for (idx=0; idx < participantList.Size(); idx++) SendOurFCMGuid(rakPeerInterface->GetSystemAddressFromGuid(participantList[idx].rakNetGuid)); } } else { if (hasRemoteFCMGuid==false) { // We have a fcmGuid they do not SendConnectionCountResponse(packet->systemAddress, totalConnectionCount+1); } else { // We both have fcmGuids IncrementTotalConnectionCount(remoteTotalConnectionCount); SendOurFCMGuid(packet->systemAddress); } } CalculateAndPushHost(); }
// Called every frame void APing::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); if(client == nullptr) { return; } p = client->Receive(); if (p == 0) { UE_LOG(RakNet_Ping, Log, TEXT("waiting data...")); return; } //waitReceivedData = false; // Check if this is a network message packet switch (p->data[0]) { case ID_UNCONNECTED_PONG: { unsigned int dataLength; RakNet::TimeMS time; RakNet::BitStream bsIn(p->data, p->length, false); bsIn.IgnoreBytes(1); bsIn.Read(time); dataLength = p->length - sizeof(unsigned char) - sizeof(RakNet::TimeMS); FString sysAddress = FString(p->systemAddress.ToString(true)); UE_LOG(RakNet_Ping, Log, TEXT("ID_UNCONNECTED_PONG from SystemAddress %s."), *sysAddress); UE_LOG(RakNet_Ping, Log, TEXT("Time is %i"), time); UE_LOG(RakNet_Ping, Log, TEXT("Data is %i bytes long"), dataLength); if (dataLength > 0) { char* charData = (char*)(p->data + sizeof(unsigned char) + sizeof(RakNet::TimeMS)); FString strData = FString(UTF8_TO_TCHAR(charData)); UE_LOG(RakNet_Ping, Log, TEXT("response string is %s, length is %d "), *strData, strlen(charData)); //GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Green, strData); OnReceivePingResponse.Broadcast(strData); } // In this sample since the client is not running a game we can save CPU cycles by // Stopping the network threads after receiving the pong. //client->Shutdown(100); } break; case ID_UNCONNECTED_PING: break; case ID_UNCONNECTED_PING_OPEN_CONNECTIONS: break; } client->DeallocatePacket(p); client = nullptr; //RakNet::RakPeerInterface::DestroyInstance(server); //RakNet::RakPeerInterface::DestroyInstance(client); //UE_LOG(RakNet_Ping, Log, TEXT("client receive response!")); }
int main() { char str[512]; RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance(); bool isServer; RakNet::Packet *packet; printf("(C)lient or (S)erver?\n"); gets(str); if ((str[0] == 'c') || (str[0] == 'C')) { RakNet::SocketDescriptor sd; peer->Startup(1, &sd, 1); isServer = false; } else { RakNet::SocketDescriptor sd(SERVER_PORT, 0); peer->Startup(MAX_CLIENTS, &sd, 1); isServer = true; } if (isServer) { printf("Starting the server.\n"); peer->SetMaximumIncomingConnections(MAX_CLIENTS); } else { printf("Enter server IP or hit enter for default: 127.0.0.1\n"); gets(str); if (str[0] == 0) { strcpy(str, "127.0.0.1"); } printf("Starting the client.\n"); peer->Connect(str, SERVER_PORT, 0, 0); } while (1) { for (packet = peer->Receive(); packet; peer->DeallocatePacket(packet), packet = peer->Receive()) { switch (packet->data[0]) { case ID_REMOTE_DISCONNECTION_NOTIFICATION: printf("Another client has dosconnected\n"); break; case ID_REMOTE_CONNECTION_LOST: printf("Another client has lost the connection\n"); break; case ID_REMOTE_NEW_INCOMING_CONNECTION: printf("Another client has connected\n"); break; case ID_CONNECTION_REQUEST_ACCEPTED: printf("Our connection request has been accepted.\n"); { RakNet::BitStream bsOut; bsOut.Write((RakNet::MessageID)ID_GAME_MESSAGE_1); bsOut.Write("Hello World"); peer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); } break; case ID_NEW_INCOMING_CONNECTION: printf("A connection is incoming.\n"); break; case ID_NO_FREE_INCOMING_CONNECTIONS: printf("The server is full.\n"); break; case ID_DISCONNECTION_NOTIFICATION: { if (isServer) { printf("A client has disconnected.\n"); } else { printf("We have been disconnected.\n"); } } break; case ID_GAME_MESSAGE_1: { RakNet::RakString rs; RakNet::BitStream bsIn(packet->data, packet->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(rs); printf("%s\n", rs.C_String()); } break; default: printf("Message with identifier %i has arrived.\n", packet->data[0]); break; } } } RakNet::RakPeerInterface::DestroyInstance(peer); return 0; }
void Update() { // Check if we are tagging enemy { if (m_ConnectedPlayers != NULL) { float length = (m_ConnectedPlayers->m_position - Graphics::GetPlayerPosition()).GetLength(); Audio::SetVolume(length, 400.0f, 100.0f); if (length < 100.0f) { eae6320::Graphics::ResetFlag(); eae6320::Graphics::ResetEnemyFlag(); eae6320::Networking::TagBitch(); } } } RakNet::Packet *packet; for (packet = m_Peer->Receive(); packet; m_Peer->DeallocatePacket(packet), packet = m_Peer->Receive()) { switch (packet->data[0]) { case ID_ENEMY_SCORE: { RakNet::BitStream bsIn(packet->data, packet->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); int Score; bsIn.Read(Score); eae6320::Graphics::SetEnemyScore(Score); Audio::PlayAudio(7); } break; case ID_ENEMY_FLAG_LOCATION: { RakNet::BitStream bsIn(packet->data, packet->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(m_EnemyFlagLocation.x); bsIn.Read(m_EnemyFlagLocation.y); bsIn.Read(m_EnemyFlagLocation.z); eae6320::Graphics::SetEnemyFlagLocation(m_EnemyFlagLocation); } break; case ID_REMOTE_DISCONNECTION_NOTIFICATION: UserOutput::Print("Another client has disconnected.\n"); break; case ID_REMOTE_CONNECTION_LOST: UserOutput::Print("Another client has lost the connection.\n"); break; case ID_REMOTE_NEW_INCOMING_CONNECTION: UserOutput::Print("Another client has connected.\n"); break; case ID_CONNECTION_REQUEST_ACCEPTED: { printf("Our connection request has been accepted.\n"); m_ServerAddress = packet->systemAddress; // Use a BitStream to write a custom user message // Bitstreams are easier to use than sending casted structures, and handle endian swapping automatically SendPlayerPosition(); } break; case ID_NEW_INCOMING_CONNECTION: UserOutput::Print("A connection is incoming.\n"); m_Clients[m_totalClients] = packet->systemAddress; m_totalClients++; SendPlayerPosition(); break; case ID_NO_FREE_INCOMING_CONNECTIONS: UserOutput::Print("The server is full.\n"); break; case ID_DISCONNECTION_NOTIFICATION: if (m_IsServer) { UserOutput::Print("A client has disconnected.\n"); } else { UserOutput::Print("We have been disconnected.\n"); } break; case ID_PLAYER_LOCATION: { CreatePlayer(); RakNet::BitStream bsIn(packet->data, packet->length, false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); float x, y, z; bsIn.Read(x); bsIn.Read(y); bsIn.Read(z); for (int i = 0; i < 10; i++) { m_ConnectedPlayers[i].m_position.x = x; m_ConnectedPlayers[i].m_position.y = y; m_ConnectedPlayers[i].m_position.z = z; } } break; case ID_TAG_BITCH: { m_ResetFlag = true; } break; case ID_CONNECTION_LOST: if (m_IsServer) { UserOutput::Print("A client lost the connection.\n"); } else { UserOutput::Print("Connection lost.\n"); } break; default: char buf[100]; sprintf_s(buf, "Message with identifier %i has arrived.\n", packet->data[0]); UserOutput::Print(buf); break; } } }
int main(int argc, char **argv) { if (argc<8) { printf("Arguments: serverIP, pathToGame, gameName, patchImmediately, localPort, serverPort, fullScan"); return 0; } RakNet::SystemAddress TCPServerAddress=RakNet::UNASSIGNED_SYSTEM_ADDRESS; RakNet::AutopatcherClient autopatcherClient; RakNet::FileListTransfer fileListTransfer; RakNet::CloudClient cloudClient; autopatcherClient.SetFileListTransferPlugin(&fileListTransfer); bool didRebalance=false; // So we only reconnect to a lower load server once, for load balancing bool fullScan = argv[7][0]=='1'; unsigned short localPort; localPort=atoi(argv[5]); unsigned short serverPort=atoi(argv[6]); RakNet::PacketizedTCP packetizedTCP; if (packetizedTCP.Start(localPort,1)==false) { printf("Failed to start TCP. Is the port already in use?"); return 1; } packetizedTCP.AttachPlugin(&autopatcherClient); packetizedTCP.AttachPlugin(&fileListTransfer); RakNet::RakPeerInterface *rakPeer; rakPeer = RakNet::RakPeerInterface::GetInstance(); RakNet::SocketDescriptor socketDescriptor(localPort,0); rakPeer->Startup(1,&socketDescriptor, 1); rakPeer->AttachPlugin(&cloudClient); DataStructures::List<RakNet::RakNetSocket2* > sockets; rakPeer->GetSockets(sockets); printf("Started on port %i\n", sockets[0]->GetBoundAddress().GetPort()); char buff[512]; strcpy(buff, argv[1]); rakPeer->Connect(buff, serverPort, 0, 0); printf("Connecting...\n"); char appDir[512]; strcpy(appDir, argv[2]); char appName[512]; strcpy(appName, argv[3]); bool patchImmediately=argc>=5 && argv[4][0]=='1'; RakNet::Packet *p; while (1) { RakNet::SystemAddress notificationAddress; notificationAddress=packetizedTCP.HasCompletedConnectionAttempt(); if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS) { printf("ID_CONNECTION_REQUEST_ACCEPTED\n"); TCPServerAddress=notificationAddress; } notificationAddress=packetizedTCP.HasNewIncomingConnection(); if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS) printf("ID_NEW_INCOMING_CONNECTION\n"); notificationAddress=packetizedTCP.HasLostConnection(); if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS) printf("ID_CONNECTION_LOST\n"); notificationAddress=packetizedTCP.HasFailedConnectionAttempt(); if (notificationAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS) { printf("ID_CONNECTION_ATTEMPT_FAILED TCP\n"); autopatcherClient.SetFileListTransferPlugin(0); autopatcherClient.Clear(); packetizedTCP.Stop(); rakPeer->Shutdown(500,0); RakNet::RakPeerInterface::DestroyInstance(rakPeer); return 0; } p=packetizedTCP.Receive(); while (p) { if (p->data[0]==ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR) { char buff[256]; RakNet::BitStream temp(p->data, p->length, false); temp.IgnoreBits(8); RakNet::StringCompressor::Instance()->DecodeString(buff, 256, &temp); printf("ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR\n"); printf("%s\n", buff); autopatcherClient.SetFileListTransferPlugin(0); autopatcherClient.Clear(); packetizedTCP.Stop(); rakPeer->Shutdown(500,0); RakNet::RakPeerInterface::DestroyInstance(rakPeer); return 0; } else if (p->data[0]==ID_AUTOPATCHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES) { printf("ID_AUTOPATCHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES\n"); autopatcherClient.SetFileListTransferPlugin(0); autopatcherClient.Clear(); packetizedTCP.Stop(); rakPeer->Shutdown(500,0); RakNet::RakPeerInterface::DestroyInstance(rakPeer); return 0; } else if (p->data[0]==ID_AUTOPATCHER_FINISHED) { printf("ID_AUTOPATCHER_FINISHED with server time %f\n", autopatcherClient.GetServerDate()); double srvDate=autopatcherClient.GetServerDate(); FILE *fp = fopen("srvDate", "wb"); fwrite(&srvDate,sizeof(double),1,fp); fclose(fp); autopatcherClient.SetFileListTransferPlugin(0); autopatcherClient.Clear(); packetizedTCP.Stop(); rakPeer->Shutdown(500,0); RakNet::RakPeerInterface::DestroyInstance(rakPeer); return 0; } else if (p->data[0]==ID_AUTOPATCHER_RESTART_APPLICATION) { printf("ID_AUTOPATCHER_RESTART_APPLICATION"); autopatcherClient.SetFileListTransferPlugin(0); autopatcherClient.Clear(); packetizedTCP.Stop(); rakPeer->Shutdown(500,0); RakNet::RakPeerInterface::DestroyInstance(rakPeer); return 0; } // Launch \"AutopatcherClientRestarter.exe autopatcherRestart.txt\"\nQuit this application immediately after to unlock files.\n"); packetizedTCP.DeallocatePacket(p); p=packetizedTCP.Receive(); } p=rakPeer->Receive(); while (p) { if (p->data[0]==ID_CONNECTION_REQUEST_ACCEPTED) { // UploadInstanceToCloud(&cloudClient, p->guid); // GetClientSubscription(&cloudClient, p->guid); GetServers(&cloudClient, p->guid); break; } else if (p->data[0]==ID_CONNECTION_ATTEMPT_FAILED) { printf("ID_CONNECTION_ATTEMPT_FAILED UDP\n"); autopatcherClient.SetFileListTransferPlugin(0); autopatcherClient.Clear(); packetizedTCP.Stop(); rakPeer->Shutdown(500,0); RakNet::RakPeerInterface::DestroyInstance(rakPeer); return 0; } else if (p->data[0]==ID_CLOUD_GET_RESPONSE) { RakNet::CloudQueryResult cloudQueryResult; cloudClient.OnGetReponse(&cloudQueryResult, p); unsigned int rowIndex; const bool wasCallToGetServers=cloudQueryResult.cloudQuery.keys[0].primaryKey=="CloudConnCount"; printf("\n"); if (wasCallToGetServers) printf("Downloaded server list. %i servers.\n", cloudQueryResult.rowsReturned.Size()); unsigned short connectionsOnOurServer=65535; unsigned short lowestConnectionsServer=65535; RakNet::SystemAddress lowestConnectionAddress; for (rowIndex=0; rowIndex < cloudQueryResult.rowsReturned.Size(); rowIndex++) { RakNet::CloudQueryRow *row = cloudQueryResult.rowsReturned[rowIndex]; if (wasCallToGetServers) { unsigned short connCount; RakNet::BitStream bsIn(row->data, row->length, false); bsIn.Read(connCount); printf("%i. Server found at %s with %i connections\n", rowIndex+1, row->serverSystemAddress.ToString(true), connCount); unsigned short connectionsExcludingOurselves; if (row->serverGUID==p->guid) connectionsExcludingOurselves=connCount-1; else connectionsExcludingOurselves=connCount; // Find the lowest load server (optional) if (p->guid==row->serverGUID) { connectionsOnOurServer=connectionsExcludingOurselves; } else if (connectionsExcludingOurselves < lowestConnectionsServer) { lowestConnectionsServer=connectionsExcludingOurselves; lowestConnectionAddress=row->serverSystemAddress; } } } // Do load balancing by reconnecting to lowest load server (optional) if (didRebalance==false && wasCallToGetServers) { if (cloudQueryResult.rowsReturned.Size()>0 && connectionsOnOurServer>lowestConnectionsServer) { printf("Reconnecting to lower load server %s\n", lowestConnectionAddress.ToString(false)); rakPeer->CloseConnection(p->guid, true); // Wait for the thread to close, otherwise will immediately get back ID_CONNECTION_ATTEMPT_FAILED because no free outgoing connection slots // Alternatively, just call Startup() with 2 slots instead of 1 RakSleep(500); rakPeer->Connect(lowestConnectionAddress.ToString(false), lowestConnectionAddress.GetPort(), 0, 0); // TCP Connect to new IP address packetizedTCP.Connect(lowestConnectionAddress.ToString(false),serverPort,false); } else { // TCP Connect to original IP address packetizedTCP.Connect(buff,serverPort,false); } didRebalance=true; } cloudClient.DeallocateWithDefaultAllocator(&cloudQueryResult); } rakPeer->DeallocatePacket(p); p=rakPeer->Receive(); } if (TCPServerAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS && patchImmediately==true) { patchImmediately=false; char restartFile[512]; strcpy(restartFile, appDir); strcat(restartFile, "/autopatcherRestart.txt"); double lastUpdateDate; if (fullScan==false) { FILE *fp = fopen("srvDate", "rb"); if (fp) { fread(&lastUpdateDate, sizeof(lastUpdateDate), 1, fp); fclose(fp); } else lastUpdateDate=0; } else lastUpdateDate=0; if (autopatcherClient.PatchApplication(appName, appDir, lastUpdateDate, TCPServerAddress, &transferCallback, restartFile, argv[0])) { printf("Patching process starting.\n"); } else { printf("Failed to start patching.\n"); autopatcherClient.SetFileListTransferPlugin(0); autopatcherClient.Clear(); packetizedTCP.Stop(); rakPeer->Shutdown(500,0); RakNet::RakPeerInterface::DestroyInstance(rakPeer); return 0; } } RakSleep(30); } // Dereference so the destructor doesn't crash autopatcherClient.SetFileListTransferPlugin(0); autopatcherClient.Clear(); packetizedTCP.Stop(); rakPeer->Shutdown(500,0); RakNet::RakPeerInterface::DestroyInstance(rakPeer); return 1; }
void ServerHost::doTick() { // Get a packet from either the server or the client for (RakNet::Packet* p = m_server->Receive(); p; m_server->DeallocatePacket(p), p=m_server->Receive()) { // We got a packet, get the identifier with our handy function unsigned char packetIdentifier = GetPacketIdentifier(p); // Check if this is a network message packet switch (packetIdentifier) { case ID_DISCONNECTION_NOTIFICATION: // Connection lost normally printf("ID_DISCONNECTION_NOTIFICATION\n"); m_peer.initServer(m_server,p->guid,p->systemAddress); onDisconnect(&m_peer); break; case ID_ALREADY_CONNECTED: // Connection lost normally printf("ID_ALREADY_CONNECTED with guid %" PRINTF_64_BIT_MODIFIER "u\n", p->guid); break; case ID_INCOMPATIBLE_PROTOCOL_VERSION: printf("ID_INCOMPATIBLE_PROTOCOL_VERSION\n"); break; case ID_CONNECTION_BANNED: // Banned from this server printf("We are banned from this server.\n"); break; case ID_CONNECTION_ATTEMPT_FAILED: printf("Connection attempt failed\n"); break; case ID_NO_FREE_INCOMING_CONNECTIONS: // Sorry, the server is full. I don't do anything here but // A real app should tell the user printf("ID_NO_FREE_INCOMING_CONNECTIONS\n"); break; case ID_INVALID_PASSWORD: printf("ID_INVALID_PASSWORD\n"); break; case ID_CONNECTION_LOST: // Couldn't deliver a reliable packet - i.e. the other system was abnormally // terminated printf("ID_CONNECTION_LOST\n"); m_peer.initServer(m_server,p->guid,p->systemAddress); onDisconnect(&m_peer); break; case ID_NEW_INCOMING_CONNECTION: // This tells the client they have connected m_peer.initServer(m_server,p->guid,p->systemAddress); onConnect(&m_peer); break; case ID_CONNECTED_PING: case ID_UNCONNECTED_PING: printf("Ping from %s\n", p->systemAddress.ToString(true)); break; case ID_USER_PACKET_ENUM: { RakNet::RakString rs; RakNet::BitStream bsIn(p->data,p->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(rs); m_peer.initServer(m_server,p->guid,p->systemAddress); onReceive(&m_peer,rs.C_String(),rs.GetLength()); } break; default: break; } } }
int main(void) { // Pointers to the interfaces of our server and client. // Note we can easily have both in the same program RakNet::RakPeerInterface *client=RakNet::RakPeerInterface::GetInstance(); RakNet::RakPeerInterface *server=RakNet::RakPeerInterface::GetInstance(); int i = server->GetNumberOfAddresses(); // Holds packets RakNet::Packet* p; // Record the first client that connects to us so we can pass it to the ping function RakNet::SystemAddress clientID=RakNet::UNASSIGNED_SYSTEM_ADDRESS; bool packetFromServer; char portstring[30]; printf("This is a sample of how to send offline pings and get offline ping\n"); printf("responses.\n"); printf("Difficulty: Beginner\n\n"); // A server puts("Enter the server port to listen on"); Gets(portstring,sizeof(portstring)); if (portstring[0]==0) strcpy(portstring,"60000"); // Enumeration data puts("Enter offline ping response data (for return by a LAN discovery for example)"); puts("Hit enter for none."); char enumData[512]; Gets(enumData,sizeof(enumData)); if (enumData[0]) server->SetOfflinePingResponse(enumData, (const unsigned int) strlen(enumData)+1); puts("Starting server."); // The server has to be started to respond to pings. RakNet::SocketDescriptor socketDescriptor(atoi(portstring),0); bool b = server->Startup(2, &socketDescriptor, 1)==RakNet::RAKNET_STARTED; server->SetMaximumIncomingConnections(2); if (b) puts("Server started, waiting for connections."); else { puts("Server failed to start. Terminating."); exit(1); } socketDescriptor.port=0; client->Startup(1,&socketDescriptor, 1); puts("'q' to quit, any other key to send a ping from the client."); char buff[256]; // Loop for input while (1) { if (kbhit()) { // Holds user data char ip[64], serverPort[30], clientPort[30]; if (Gets(buff,sizeof(buff))&&(buff[0]=='q')) break; else { // Get our input puts("Enter the client port to listen on, or 0"); Gets(clientPort,sizeof(clientPort)); if (clientPort[0]==0) strcpy(clientPort, "0"); puts("Enter IP to ping"); Gets(ip, sizeof(ip)); if (ip[0]==0) strcpy(ip, "127.0.0.1"); puts("Enter the port to ping"); Gets(serverPort,sizeof(serverPort)); if (serverPort[0]==0) strcpy(serverPort, "60000"); client->Ping(ip, atoi(serverPort), false); puts("Pinging"); } } // Get a packet from either the server or the client p = server->Receive(); if (p==0) { packetFromServer=false; p = client->Receive(); } else packetFromServer=true; if (p==0) continue; // Check if this is a network message packet switch (p->data[0]) { case ID_UNCONNECTED_PONG: { unsigned int dataLength; RakNet::TimeMS time; RakNet::BitStream bsIn(p->data,p->length,false); bsIn.IgnoreBytes(1); bsIn.Read(time); dataLength = p->length - sizeof(unsigned char) - sizeof(RakNet::TimeMS); printf("ID_UNCONNECTED_PONG from SystemAddress %s.\n", p->systemAddress.ToString(true)); printf("Time is %i\n",time); printf("Ping is %i\n", (unsigned int)(RakNet::GetTimeMS()-time)); printf("Data is %i bytes long.\n", dataLength); if (dataLength > 0) printf("Data is %s\n", p->data+sizeof(unsigned char)+sizeof(RakNet::TimeMS)); // In this sample since the client is not running a game we can save CPU cycles by // Stopping the network threads after receiving the pong. client->Shutdown(100); } break; case ID_UNCONNECTED_PING: break; case ID_UNCONNECTED_PING_OPEN_CONNECTIONS: break; } // We're done with the packet if (packetFromServer) server->DeallocatePacket(p); else client->DeallocatePacket(p); } // We're done with the network RakNet::RakPeerInterface::DestroyInstance(server); RakNet::RakPeerInterface::DestroyInstance(client); return 0; }
void NetworkEngine::updatePlayerList(RakNet::Packet * packet) { RakNet::BitStream bsIn(packet->data,packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); //En otros sitios esta como bsIn.IgnoreBytes(1), es lo mismo unsigned short size; bsIn.Read(size); /*std::vector<PlayerInfo> playerListTemp; playerListTemp.push_back(playerList); */ playerList.clear(); for(int i=0;i< size;i++) { PlayerInfo player; //RakNet::SystemAddress ip; bsIn.Read(player.guid); //player.guid = ip; RakNet::RakString string; bsIn.Read(string); player.name = string; unsigned short ping; bsIn.Read(ping); player.ping = ping; bool ready = false; bsIn.Read(ready); player.ready = ready; RakNet::RakString string2; bsIn.Read(string2); player.character = string2; playerList.push_back(player); } GraphicsEngine* graphicsEngine = GameManager::getInstance()->getGraphicsEngine(); graphicsEngine->updateTablePlayers(playerList); unsigned int readys = 0; for(std::size_t i = 0; i < playerList.size(); i++) { if(playerList[i].ready && !playerList[i].character.IsEmpty()) { readys++; } } if(readys >= playerList.size()) { graphicsEngine->putBegin(true); } else { graphicsEngine->putBegin(false); } }
void NPC::UpdateRaknet(Packet* packet, RakPeerInterface* peer) { switch (packet->data[0]) { case ID_NPC_POSITION: { int arrayIndex = 0; int pathIndex = 0; SVector2 position(0.0f, 0.0f); BitStream bsIn(packet->data, packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(arrayIndex); bsIn.Read(pathIndex); bsIn.Read(position); int mapID = mCurrentPlayers.GetPlayer(packet->guid)->GetMap(); MapData* map = mActiveMaps.GetMap(mapID); map->SetNPCPath(arrayIndex, pathIndex); map->SetNPCPosition(arrayIndex, position); break; } case ID_NPC_NEW_PATH: { int npcIndex; int endIndex; SVector2 position; BitStream bsIn(packet->data, packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(npcIndex); bsIn.Read(endIndex); bsIn.Read(position); int map = mCurrentPlayers.GetPlayer(packet->guid)->GetMap(); MapData* tempMap = mActiveMaps.GetMap(map); tempMap->SetNPCEndIndex(npcIndex, endIndex); tempMap->SetNPCPosition(npcIndex, position); mCurrentPlayers.SendNewPath(map, npcIndex, endIndex, position); break; } case ID_NPC_STOP: { int npcIndex = 0; bool stop = false; BitStream bsIn(packet->data, packet->length,false); bsIn.IgnoreBytes(sizeof(RakNet::MessageID)); bsIn.Read(npcIndex); bsIn.Read(stop); if(stop) printf("NPC Stopped\n"); else printf("NPC Started\n"); int map = mCurrentPlayers.GetPlayer(packet->guid)->GetMap(); mActiveMaps.GetMap(map)->SetNPCStop(npcIndex, stop); mCurrentPlayers.SendNPCStop(packet, peer, npcIndex, stop, map); break; } } }