Example #1
0
int UDPManager::sendDatagram(DataBuffer * data, unsigned long ipAddress, unsigned long port, unsigned long frameCount) {
	if (initErrors || data == NULL || port == 0) return -1;

	sockaddr_in otherAddress;
	otherAddress.sin_family = AF_INET;
	otherAddress.sin_addr.s_addr = ipAddress;
	otherAddress.sin_port = port;

	int packetSize = data->getSize();
	DataBuffer * sendBuffer = new DataBuffer(packetSize + 4);
	//sendBuffer->copy(0, &packetSize, sizeof(int));
	sendBuffer->copy(0, &frameCount, 4);
	sendBuffer->copy(4, data->getData(), data->getSize());

	if (sendto(sock, sendBuffer->getData(), sendBuffer->getSize(), 0, (struct sockaddr *)&otherAddress, sizeof(otherAddress)) < 0) {
		perror("UDP sendto() failed\n");
		delete sendBuffer;
		return -1;
	}

	//printf("UDP Send:");
	//Utilities::printfNetworkPacket(sendBuffer->getData(), sendBuffer->getSize());
	delete sendBuffer;

	return 0;
}
Example #2
0
int Server::synchClient(int clientID)
{
	//aquireClientsMutex(clientID);
		//Clear Objects
		DataBuffer * temp = NetworkFunctions::createClearObjectsBuffer();
		clients[clientID]->pushSendData(temp->getData(), temp->getSize());
		delete temp;

		//Add Existing Objects
		for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
			temp = NetworkFunctions::createCreateObjectBuffer(iter->second);
			clients[clientID]->pushSendData(temp->getData(), temp->getSize());
			delete temp;
		}
		/*for (int i = 0; i < gameObjects->size(); i++) {
			temp = NetworkFunctions::createCreateObjectBuffer(gameObjects->at(i));
			clients[clientID]->pushSendData(temp->getData(), temp->getSize());
			delete temp;
		}*/

		for (int i = 0; i < playerObjects->size(); i++) {
			if (playerObjects->at(i) != NULL) {
				//Add All Existing Spells to players
				/*for (int elementIndex = 0; elementIndex < 5; elementIndex++) {
					for (int subIndex = 0; subIndex < playerObjects->at(i)->getSpells()[elementIndex].size(); subIndex++) {
						Spell * tempSpell = playerObjects->at(i)->getSpell(elementIndex, subIndex);
						if (tempSpell != NULL) {
							temp = NetworkFunctions::createAddSpellBuffer(clientID, elementIndex, tempSpell->getSpellID());
							clients[clientID]->pushSendData(temp->getData(), temp->getSize());
						}
					}
				}*/

				//Change Spell to active one
				int currentElementIndex, currentSubIndex;
				playerObjects->at(i)->getActiveSpellIndices(&currentElementIndex, &currentSubIndex);
				temp = NetworkFunctions::createChangeSpellBuffer(i, currentElementIndex, currentSubIndex);
				clients[clientID]->pushSendData(temp->getData(), temp->getSize());
			}
		}
		//send all the items to create
	//releaseClientsMutex(clientID);

	return 0;
}
Example #3
0
void Texture::create(char *name, char *filename, unsigned char relativePath, unsigned int flags,
		unsigned char filter, float anisotropicFilter) {
	strcpy(this->name, name);
	DataBuffer *dataBuffer = new DataBuffer();
	dataBuffer->read(filename, relativePath);
	if (dataBuffer->getSize()) {
		load(dataBuffer);
		generateId(flags, filter, anisotropicFilter);
		freePixel();
		delete dataBuffer;
	}
}
Example #4
0
// ---------------------------------------------
void testSocket(string ip, unsigned short port) {
    Socket* socket = new Socket("null", 0);

    Socket::InetAddressPort remoteAddrAndPort;
    remoteAddrAndPort.port = port;
    Socket::getSockaddrByIpAndPort(&remoteAddrAndPort.addr, ip, port);

    socket->makeNonBlocking();
    while (true) {
        bool result  = socket->connect(remoteAddrAndPort);
        if (result) {
            cout << "connect success!" << endl;

            cm::Thread::sleep(100);

            char sendData[] = "TCP client request";
            int numberOfBytesSent;
            if (SKT_SUCC == socket->send(sendData, strlen(sendData), numberOfBytesSent)) {
                assert(numberOfBytesSent == strlen(sendData));
                cout << "send " << numberOfBytesSent << " bytes data complete" << endl;

                DataBuffer* response = new DataBuffer();
                int numOfBytesRecved = 0;

                while (true) {
                    result = socket->recv(response->getEndOfDataPointer(), response->getSize() - response->getLength(), numOfBytesRecved);
                    assert(result != SKT_ERR);
                    if (result == SKT_SUCC) {
                        assert(numOfBytesRecved != 0);
                        response->increaseDataLength(numOfBytesRecved);
                        cout << "recv " << numOfBytesRecved << " bytes data: " << response->getData() << endl;
                        response->reset();
                        break;
                    } else {
                        cm::Thread::sleep(1);
                    }
                }
            }

            socket->close();
            break;
        } else {
            cm::Thread::sleep(1);
        } 
    }
}
Example #5
0
int Server::run(const char * ini)
{
	readServerData(ini);

	//clients = new Client[maxPlayers];
	clients = vector<Client*>();
	clients.reserve(maxPlayers);
	for (int i = 0; i < maxPlayers; i++) {
		clients.push_back(new Client());
		clients[i]->setID(i);
	}
		
	double elapsedTime = 0.0;
	double timePerFrame = 1000.0 / updateRate;
	double timePerRenderFrame = 1000.0 / renderRefreshRate;
	static double timeSinceLastRender = 0.0;
	long lastTime = 0;

	double targetSleep = 0.0;
	double sleepRemainder = 0.0;
	double startSleep = 0.0;
	double sleepTime = 0.0;

	loadConfig();
	initSDL();
	initGlew();
	initBullet();
	initGLContexts();
	initObjects();
	
	running = true;
	HANDLE listenThreadHandle = HostListener::start();

	loadResources();
	loadLevel("asdf");

	while (running) {
		frameCount++;
		if (GetAsyncKeyState(VK_ESCAPE) && (GetForegroundWindow() == consoleWindow) &&
			MessageBox(0, "Shutdown the Server?", "Rune Server Shutdown", MB_YESNO) == IDYES) break;

		lastTime = lastTime = SDL_GetTicks();

		serverEventsTCP->clearSendBuffer();
		serverEventsTCP->clearReceiveBuffer();
		serverEventsUDP->clearSendBuffer();
		serverEventsUDP->clearReceiveBuffer();

		//Get all commands from clients
		for (int i = 0; i < maxPlayers; i++) {
			DataBuffer * temp;
			aquireClientsMutex(i);
				temp = clients[i]->popReceiveData();
				if (!clients[i]->isConnected() && playerObjects->at(i) != NULL) {
					int index = -1;
					int x = 0;
					for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
						if (playerObjects->at(i) == iter->second) {
							index = x;
							break;
						}
						x++;
					}
					/*for (int x = 0; x < gameObjects->size(); x++) {
						if (playerObjects->at(i) == gameObjects->at(x))
							index = x;
					}*/
					gameObjects->remove(playerObjects->at(i)->getNetID());
					delete playerObjects->at(i);
					playerObjects->at(i) = NULL;
					//gameObjects->erase(gameObjects->begin() + index);
					serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(index));
				}
			releaseClientsMutex(i);
			serverEventsTCP->appendToReceiveBuffer(temp);
		}

		//Receive All UDP Events
		sockaddr_in * originAddress = NULL;
		DataBuffer * udpBuffer = UDPManager::recvDatagram(&originAddress);
		while (udpBuffer != NULL) {
			//origin Address matches client address?
			unsigned long packetFrameCount = 0;
			memcpy(&packetFrameCount, udpBuffer->getData(), 4);

			int clientID = getClientIDByAddress(originAddress->sin_addr.s_addr, originAddress->sin_port);
			if (clientID == -1) {
				int asdfadsfasdf = 123123;
			}
			else {
				//compare clientFrameCount to client->frameCount
				unsigned long clientFrameCount;
				aquireClientsMutex(clientID);
					clientFrameCount = clients[clientID]->getFrameCount();
				releaseClientsMutex(clientID);

				if (packetFrameCount < clientFrameCount) {
					//discard
					printf("Packet from Client %d discarded\n", clientID);
				}
				else {
					serverEventsUDP->appendToReceiveBuffer(udpBuffer->getData() + 4, udpBuffer->getSize() - 4);
					aquireClientsMutex(clientID);
						clients[clientID]->setFrameCount(packetFrameCount);
					releaseClientsMutex(clientID);
				}

			}
			
			delete udpBuffer; udpBuffer = NULL;
			delete originAddress; originAddress = NULL;
			udpBuffer = UDPManager::recvDatagram(&originAddress);
		}

		NetworkFunctions::translateReceivedEvents(serverEventsTCP);
		NetworkFunctions::translateReceivedEvents(serverEventsUDP);
		
		//Execute my own gamelogic commands
		SDL_Event e;
		while (SDL_PollEvent(&e)) { 
			if (e.key.keysym.sym == SDLK_ESCAPE)
						running = false;
			if (e.key.keysym.sym == SDLK_m) {
				((RigidObject*)gameObjects->getValue(2))->setPosition(5, 10, 0);
				((RigidObject*)gameObjects->getValue(3))->setPosition(0, 10, 0);
				((RigidObject*)gameObjects->getValue(4))->setPosition(-5, 10, 0);
				((RigidObject*)gameObjects->getValue(2))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(3))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(4))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(2))->setGravity(0, -9.81f*4.0f, 0);
				((RigidObject*)gameObjects->getValue(3))->setGravity(0, -9.81f*4.0f, 0);
				((RigidObject*)gameObjects->getValue(4))->setGravity(0, -9.81f*4.0f, 0);
				printf("reset boxes\n");
			}
		}

		//if (update((long)(elapsedTime + sleepTime)) == -1) break;

		//dynamicsWorld->stepSimulation((float)(elapsedTime + sleepTime)*0.001f, 50, (float)(elapsedTime + sleepTime)*0.001f);
		dynamicsWorld->stepSimulation(1.0f / 64.0f, 100, 1.0f / 64.0f); //1.0f/(float)Settings::getMaxFPS());

		list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin();
		while (iter != gameObjects->end())
		{
			iter->second->update(elapsedTime);
			if (!iter->second->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(iter->second->getNetID()));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == iter->second) {
						playerObjects->at(p) = NULL;
					}
				}

				GameObject * tempObject = iter->second;
				iter = gameObjects->erase(iter);
				delete tempObject;
			}
			else iter++;
		}

		/*for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
			iter->second->update(elapsedTime);
			if (!iter->second->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(iter->second->getNetID()));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == iter->second) {
						playerObjects->at(p) = NULL;
					}
				}

				gameObjects->remove(iter->first, iter->second);
				delete (*gameObjects)[i];
				gameObjects->erase(gameObjects->begin() + i);
				i--;
			}
		}*/

		/*for (int i = 0; i < (int)gameObjects->size(); i++) {
			(*gameObjects)[i]->update(elapsedTime);
			if (!(*gameObjects)[i]->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(i));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == (*gameObjects)[i]) {
						playerObjects->at(p) = NULL;
					}
				}
				delete (*gameObjects)[i];
				gameObjects->erase(gameObjects->begin() + i);
				i--;
			}
		}*/
		
		//Update each client
		//for (int i = 0; i < gameObjects->size(); i++)
		//	serverEvents->appendToSendBuffer(NetworkFunctions::createUpdateObjectBuffer(i));

		for (int i = 0; i < maxPlayers; i++) {
			aquireClientsMutex(i);
				if (clients[i]->isConnected()) {
					if (clients[i]->requiresSynch()) {
						synchClient(i);
						clients[i]->setSynch(false);
					}
					else {
						clients[i]->pushSendData(serverEventsTCP->getSendBuffer(), serverEventsTCP->getSendBufferSize());
					}
				}
			releaseClientsMutex(i);
		}
		
		for (int i = 0; i < maxPlayers; i++) {
			aquireClientsMutex(i);
			if (clients[i]->isConnected()) {
				//unsigned long clientPortUDP = clients[i]->getPortUDP();
				if (!clients[i]->requiresSynch()) {
					serverEventsUDP->clearSendBuffer();
					for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
						if (playerObjects->at(i) != iter->second /* && dont force player */) {
							DataBuffer * temp = NetworkFunctions::createUpdateObjectBuffer(iter->second->getNetID());
							serverEventsUDP->appendToSendBuffer(temp);
						}
					}
					UDPManager::sendDatagram(serverEventsUDP->getSendBuffer(), serverEventsUDP->getSendBufferSize(), clients[i]->getIPAddress(), clients[i]->getPortUDP(), frameCount);
				}
			}
			releaseClientsMutex(i);
		}

		/*timeSinceLastRender += elapsedTime;
		if (timeSinceLastRender >= timePerRenderFrame) {
			timeSinceLastRender = 0.0;
			renderFrame();
		}*/
		renderFrame();

		//Update Rate Calculations
		//Framerate Limit Calculations
		elapsedTime = SDL_GetTicks() - lastTime;
		targetSleep = timePerFrame - elapsedTime + sleepRemainder;
		if (targetSleep > 0) sleepRemainder = targetSleep - (Uint32)targetSleep;

		//Sleep(1000.0 / 64.0);
		
		startSleep = SDL_GetTicks();
		while ((Uint32)(startSleep + targetSleep) > SDL_GetTicks());
		sleepTime = SDL_GetTicks() - startSleep;
	}

	cout << "Shutting Down\n";
	HostThread::stopAll();
	HostListener::stop();
	UDPManager::cleanup();
	WSACleanup();
	WaitForSingleObject(listenThreadHandle, INFINITE);

	saveConfig();

	cleanupObjects();
	//saveConfig();
	killBullet();
		
	//delete [] clients;
	
	return 0;
}
Example #6
0
DataBuffer::DataBuffer(const DataBuffer &dataBuffer, std::size_t offset, std::size_t count)
{
	count = offset + count >= dataBuffer.getSize() ? dataBuffer.getSize() - offset : count;
	_data.reserve(count);
	std::copy(dataBuffer._data.begin() + offset, dataBuffer._data.begin() + offset + count, std::back_inserter(_data));
}
Example #7
0
int NetworkFunctions::translateReceivedEvents(Packet * serverEvents)
{
	while (serverEvents->getReceiveBufferSize() > 0) {
		DataBuffer * tempBuffer = new DataBuffer(MAX_PACKET_SIZE);

		int charCount = 0;
		int functionIndex = -1;
		int bufferLength = -1;
		for (int i = 0; i < serverEvents->getReceiveBufferSize(); i++) {
			tempBuffer->copy(tempBuffer->getSize(), serverEvents->getReceiveBuffer() + i, 1);

			if (charCount == 3) {
				memcpy(&functionIndex, tempBuffer->getData(), 4);
				if (functionIndex < 0 || functionIndex >= FUNCTION_COUNT || functionIndex == 10) {
					while ((serverEvents->getReceiveBuffer()[i]) != '\n') i++;
					tempBuffer->clear();
					continue;
				}
				else {
					bufferLength = bufferSizes[functionIndex];
				}
			}

			if (charCount == 7 && functionIndex == EVENT_UPDATE_GAME_OBJECT) {
				unsigned long netID = 0;
				memcpy(&netID, tempBuffer->getData() + 4, 4);
				GameObject * tempObject = gameObjects->getValue(netID);
				if (tempObject == NULL) {
					while ((serverEvents->getReceiveBuffer()[i]) != '\n') i++;
					tempBuffer->clear();
					continue;
				}
				/*int objectIndex = -1;
				memcpy(&objectIndex, tempBuffer->getData() + 4, 4);
				if (objectIndex < 0 || objectIndex >= gameObjects->size()) {
					while ((serverEvents->getReceiveBuffer()[i]) != '\n') i++;
					tempBuffer->clear();
					continue;
				}*/
				else {
					bufferLength = tempObject->getSerializedSize();
				}
			}

			if (charCount == bufferLength-1) {
				if (tempBuffer->getSize() == 0) {
					tempBuffer->clear();
					continue;
				}

				executeIndexedFunction(tempBuffer);
				tempBuffer->clear();
				charCount = 0;
				continue;
			}

			/*if (serverEvents->getReceiveBuffer()[i] == '\n') {
				if (tempBuffer->getSize() == 0) {
					tempBuffer->clear();
					continue;
				}

				executeIndexedFunction(tempBuffer);

				tempBuffer->clear();
			}*/
			charCount++;
		}
		delete tempBuffer;
		serverEvents->refillReceiveBuffer();
	}
	return 0;
}