Exemple #1
0
int main(void)
{
	RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance();
	bool isServer;
	RakNet::Packet *packet;

	RakNet::SocketDescriptor sd( SERVER_PORT,0 );
	peer->Startup( MAX_CLIENTS, &sd, 1 );
	isServer = true;

	printf( "Starting the server.\n" );
	// We need to let the server accept incoming connections from the clients
	peer->SetMaximumIncomingConnections( MAX_CLIENTS );

	while (1)
	{
		for( packet=peer->Receive(); packet; peer->DeallocatePacket(packet), packet=peer->Receive() )
		{
			handlePacket( packet, peer );
		}
	}

	RakNet::RakPeerInterface::DestroyInstance( peer );

	return 0;
}
Exemple #2
0
// get some data
void Connection::handleRead(const boost::system::error_code& error, size_t len)
{
	if(!error)
	{
		LOGNET() << ">>> got " << len << " data from " 
				<<"id"<<m_id
				<<LOGEND();
		m_offSet += len;
		m_msgBuffer.push_back(std::string(m_buffer, m_buffer+m_offSet));
		m_offSet = 0;
		// continue to read
		tryRead();
		handlePacket();
	}
	else
	{
		if (m_status == CONN_STATUS_CONNECTED)
		{
			m_status = CONN_STATUS_DISCONNECT;
		}
		else
		{
			// triggered by other event
		}
		
		if (m_writeStatus != SW_STATUS_WRITTING)
		{
			m_errHandler(error, this, "handleread");
		}
		else
		{
			// write callback will call immediately
		}
	}
}
Exemple #3
0
int
runDaemon(int debug)
{
  char			packetPtr[PACKETLEN];
  size_t	       	packetSize;
  struct sockaddr_in	sa;

  if (checkOtherProcess())
    return (EXIT_FAILURE);
  signal(SIGTERM, sigHandler);
  signal(SIGINT, sigHandler);
  signal(SIGUSR1, sigHandler);

  if (!debug) {
    daemon(1, 1);
    if (savePid())
      return EXIT_FAILURE;
  }

  fprintf(stderr, "Daemon started\n");

  initConnection(&sa);
  while (1) {
    setClient(acceptClient(&sa));
    bzero(packetPtr, PACKETLEN);
    getPacket(packetPtr, &packetSize);
    handlePacket(packetPtr, packetSize);
    setClient(-1);
  }
  setSock(-1);
  return EXIT_SUCCESS;
}
Exemple #4
0
/*
 * Handle incoming data.  If we have a full packet in the buffer, process it.
 */
static bool handleIncoming(Peer* pWritePeer, Peer* pReadPeer)
{
    if (haveFullPacket(pReadPeer)) {
        if (pReadPeer->awaitingHandshake) {
            printf("Handshake [%c]: %.14s\n",
                pReadPeer->label[0], pReadPeer->inputBuffer);
            if (write(pWritePeer->sock, pReadPeer->inputBuffer,
                    kMagicHandshakeLen) != kMagicHandshakeLen)
            {
                fprintf(stderr,
                    "+++ [%c] handshake write failed\n", pReadPeer->label[0]);
                goto fail;
            }
            consumeBytes(pReadPeer, kMagicHandshakeLen);
            pReadPeer->awaitingHandshake = false;
        } else {
            if (!handlePacket(pWritePeer, pReadPeer))
                goto fail;
        }
    } else {
        /*printf("*** %c not full yet\n", pReadPeer->label[0]);*/
    }

    return true;

fail:
    return false;
}
void MobileDClient::slotIncomingPacket()
{
	unsigned int bytesAvailable = socket->bytesAvailable();

	// Commands have at least 4 words (=16 byte)
	if(bytesAvailable < 16)
		return;

	// There might be multiple packets waiting in the buffer. Do NOT copy the whole
	// buffer into ONE packet. We have to look for the packetLength first, which is
	// located at bytes 4,5,6,7 (see packet.h documentation for header layout).
	QByteArray packetHeader = socket->read(8);
	unsigned int packetLength = *(unsigned int*)(packetHeader.constData() + 4);

	// we can now read the whole packet into a buffer.
	QByteArray packetComplete(packetHeader);
	packetComplete.append(socket->read(packetLength - 8));

	Packet packet;
	packet.setData((const unsigned char*)packetComplete.data(), packetComplete.size());

	if(packet.isValid())
		handlePacket(&packet);
	else
		logger->MobileDClient("MobileDClient::slotIncomingPacket(): received an invalid packet.");

	// If there is more data waiting (for another packet), then make sure its fetched ASAP.
	if(socket->bytesAvailable() > 0)
	{
		logger->MobileDClient("MobileDClient::slotIncomingPacket(): There's %d more bytes waiting, re-scheduling myself.", socket->bytesAvailable());
		QTimer::singleShot(0, this, SLOT(slotIncomingPacket()));
	}
}
void *receiveThread(void *p)
{
	char buffer[PACKET_SIZE];
	int len;
	TPacket packet;
	TResult result;
	int counter=0;

	while(1)
	{
		len = serialRead(buffer);
		counter+=len;
		if(len > 0)
		{
			result = deserialize(buffer, len, &packet);

			if(result == PACKET_OK)
			{
				counter=0;
				handlePacket(&packet);
			}
			else 
				if(result != PACKET_INCOMPLETE)
				{
					printf("PACKET ERROR\n");
					handleError(result);
				}
		}
	}
}
/*------------------------------------------------------------------------------*/
void GRConnection::testPacket(wxString filename)
{
	wxFile *file = new wxFile();
	GR_PACKET_HEADER header;
	GR_PACKET packet;
	wxUint8 *buf;
	wxUint32 len;

	if(!file->Exists(filename)) 
	{
		delete(file);
		return;
	}

	file->Open(filename, wxFile::read);

	len = file->Length();
	buf = new wxUint8[len];

	file->Read(buf, (wxUint32)len);

	memcpy(&header, buf, sizeof(GR_PACKET_HEADER));
	header.command = ntohl(header.command);
	header.payloadLength = ntohl(header.payloadLength);

	packet.header = &header;
	packet.payload = (wxUint8*)buf+sizeof(GR_PACKET_HEADER);

	handlePacket(&packet);

	file->Close();
	delete[] buf;
	delete(file);
}
Exemple #8
0
void Server::updateNet() {
	ENetEvent event;
	while (enet_host_service(host, &event, 0) > 0) {
		switch (event.type) {
		case ENET_EVENT_TYPE_CONNECT:
			handleConnect(event.peer);
			break;
		case ENET_EVENT_TYPE_DISCONNECT:
			handleDisconnect(event.peer, (DisconnectReason) event.data);
			break;
		case ENET_EVENT_TYPE_RECEIVE:
			handlePacket(
				event.packet->data,
				event.packet->dataLength,
				event.channelID,
				event.peer
				);
			enet_packet_destroy(event.packet);
			break;
		default:
			LOG_WARNING(logger) << "Received unknown ENetEvent type << event.type";
			break;
		}
	}
}
Exemple #9
0
void *ClientFunction(void* client_t){
	int client = *(int*)client_t;
	int mappedID = mappedClient[client];
	printf("Client %d connected (maps to %d)\n", client, mappedID);
	unsigned char* buffer = calloc(1024,1);
	for(;;){
		read(msgsock[client], buffer, 1024);
		//char* cBuff = ScratchToNormal(buffer);
		//printf("Survival\n");
		//printf("Num: %d\n",cBuff[0]);
		//if(cBuff[0] != -1){
		//	printf("Not -1\n");
		//	printf("cBuff: %s\n",cBuff);
			int i = handlePacket(client, buffer);
			if(i == 0)
				break;
		//} else {
			printf("No packets here\n");
	//	}
		bzero(buffer, 1024);
		fflush(stdout);
	}
	printf("Dead user: %d\n", client);
	close(msgsock[client]); // bad
	msgsock[client] = 0;
	printf("Closed user: %d\n", client); // dead code
	free(buffer);
	
	accountLegal[mappedID] = 0;
	
	pthread_exit(NULL);
}
void Audio_Queue::enqueueCachedData()
{
    assert(!m_waitingOnBuffer);
    assert(!m_bufferInUse[m_fillBufferIndex]);
    
    /* Queue up as many packets as possible into the buffers */
    queued_packet_t *cur = m_queuedHead;
    while (cur) {
        int ret = handlePacket(cur->data, &cur->desc);
        if (ret == 0) {
           break; 
        }
        queued_packet_t *next = cur->next;
        free(cur);
        cur = next;
    }
    m_queuedHead = cur;
    
    /* If we finished queueing all our saved packets, we can re-schedule the
     * stream to run */
    if (cur == NULL) {
        m_queuedTail = NULL;
        if (m_delegate) {
            m_delegate->audioQueueUnderflow();
        }
    }
}
void Server::execute(){

  /* Enable the server to begin accepting clients */
  setListening(true);

  do{
    handleConnections();
  }while( current_connected_players != max_connected_players );

  /* Randomly assign player ids */
  assignIds();

  /* Signal all players that the game is ready to Begin */
  broadcastPacket(PacketFactory::GAMESTART);

  /* Send out the packets for the Dictionary Data */
  broadcastPacket(PacketFactory::TROOPDEF);

  bool keep_playing = true;


  // send init packet for first turn
  sendPacket(PacketFactory::TURNSTART, 0);

  while( keep_playing ){
     keep_playing = handlePacket();
     // std::cout << "keep_playing" << keep_playing << std::endl;
  }
}
Exemple #12
0
void MIDIMsgHandler::handlePacketList(const MIDIPacketList *list) {
    MIDIPacket *packet = (MIDIPacket *)&list->packet[0];
    for (int i = 0; i < list->numPackets; ++i) {
        handlePacket(packet);
        packet = MIDIPacketNext(packet);
    }
}
Exemple #13
0
/*********************************************************************************************
 * Initial bootup task to connect to Base Station
 * 		* Connect to Base Station 		- Send Ping packet
 * 		* Wait for response 			- Receive Ack packet
 * 		* If successful					- Turn on WiFi LEDs
 *********************************************************************************************/
void prvConnectTask( void *pvParameters ) {

	// Let task run infinitely
	for(;;) {

		// Wait for a Ping from an SAV
		if( process_packet ) {

			// Create local string to represent the packet
			char* packet = pvPortMalloc( MAX_LENGTH*sizeof(uint8_t) );

			// Pop packet from queue
			xQueueReceive( xPacketQueue, packet, 0 );

			// Process packet
			PacketResult packet_result = handlePacket( packet );

			// Free variables
			vPortFree( packet );

			if( (packet_result.result == SUCCESS) && (packet_result.type == ping) ) {

				// Reset process_packet
				process_packet = FALSE;

				// Move on to next task
				xTaskCreate( prvTrafficLightTask, "", 300 * sizeof(uint8_t), NULL, trafficLightPriority, xTrafficLightHandle );

				// Delete this task
				vTaskDelete( xConnectHandle );
			}
		}
	}
}
Exemple #14
0
int main() {
	Packet *packet = createPacket();
	if (packet != NULL) {
		destroyPacket(&packet);
		handlePacket(packet);
	}
	return 0;
}
static void poll()
{    
  uint32_t wrap = 0;
  uint32_t cur_bytes = 0;
  uint32_t total_bytes = 0;
  uint32_t cumulative_bytes = 0;
  MUHWI_PacketHeader_t *hdr = 0;

  while ((total_bytes = MUSPI_getAvailableBytes (_rfifoShadowPtr, &wrap)) != 0) 
  {
    if (wrap == 0) 
    {
      /* No fifo wrap.  Process each packet. */
      cumulative_bytes = 0;
      while (cumulative_bytes < total_bytes ) 
      {
	hdr = MUSPI_getNextPacketOptimized (_rfifoShadowPtr, &cur_bytes);

	/* Handle the packet by 
	 * - marking the associated request complete
	 * - if this is the last request (largest), increment iteration count
	 */
	handlePacket(hdr);
	
	cumulative_bytes += cur_bytes;
	/* Touch head for next packet. */
      }
    }
    else 
    {
      /* Packets wrap around to the top of the fifo.  Handle the one packet
       * that wraps.
       */
      hdr = MUSPI_getNextPacketWrap (_rfifoShadowPtr, &cur_bytes);
	/* Handle the packet by 
	 * - marking the associated request complete
	 * - if this is the last request (largest), increment iteration count
	 */
      handlePacket(hdr);
    }

    /* Store the updated fifo head. */
    MUSPI_syncRecFifoHwHead (_rfifoShadowPtr);
  }
}
Exemple #16
0
void readPackets() {

	unsigned char buffer[2048];
	recvlen = recvfrom(fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&remaddr, &addrlen);
	
	if (recvlen > 0) 
		handlePacket(buffer);
	
}
Exemple #17
0
int 
NetlinkLoopback::sendPacket(NetworkIface *iface, Packet *p)
{
	handlePacket(iface, p);
	
	iface->TxBytes += p->Size;

	return p->Size;	
}
Exemple #18
0
void RF24Mesh::fastloop()
{
	// Pump the network regularly
	  updateNetworkTopology();

	  listenRadio();

	  handlePacket();
}
Exemple #19
0
void PcapReader::
run()
{
  std::ifstream ifl(_fname.c_str(), std::ifstream::in|std::ifstream::binary);

  if (!ifl) {
    std::cerr << "PcapReader::run. Unable to open input file: " << _fname << std::endl;
    return;
  }

  PcapHeader hdr;
  PcapPktHeader pktHdr;

  // Read file header
  if (!ifl.read((char*)&hdr, sizeof(PcapHeader))) {
    std::cerr << "PcapReader::run. Unable to read file header: " << _fname << std::endl;
    ifl.close();
    return;
  }

  uint64_t bread=0; // No of bytes read
  uint64_t maxBufLen = hdr._snapLen; // Max buffer length
  char* buffer = new char[maxBufLen];
  uint64_t blen;
  int rv;

  while (ifl) {

      // read packet header
      if (!ifl.read((char*)&pktHdr, sizeof(PcapPktHeader))) {
        std::cout << "PcapReader::run. Cant rad PcapPktHeader." << std::endl;
        ifl.close();
        return;
      }
      bread += ifl.gcount();

      blen = pktHdr._incLen;
   
      // read the packet
      if (!ifl.read(buffer, blen)) {
          std::cout << "PcapReader::run. Cant read packet" << std::endl;
          ifl.close();
          return;
      }
      rv = ifl.gcount();
      bread += rv;

      // Parse the packet to remove all Network headers
      handlePacket(buffer, blen);
  }

  ifl.close();

  std::cout << "PcapReader::run. Close file and exit..." << std::endl;
}
Exemple #20
0
void listen(){
  ReplfsEvent event;
  ReplfsPacket packet;
  event.packet = &packet;
  while(true){
    nextEvent(&event);
    if(event.type == HEARTBEAT_EVENT){
    }else{
      handlePacket(&(packet.body),packet.type);
    }
  }
}
Exemple #21
0
void Connection::Server::update() {
	std::lock_guard<std::recursive_mutex> lock(*this);
	if (state != SETUP) {
		if (clients.empty()) {
			state = END;
			return;
		}
	}
	if (state == SETUP && !listeners.empty()) {
		try {
			metaserver.sendGame(*this);
		} catch (...) {
			// FIXME: Something went wrong, log it and tell the user!
		}
	}
	for (ListenerContainerType::iterator i = listeners.begin(); i != listeners.end();) {
		ListenerContainerType::iterator j = i++;
		Listener& listener = **j;
		if (!listener.update(*this)) {
			listeners.erase(j);
		}
	}
	for (ClientInfoContainerType::iterator i = clients.begin(); i != clients.end();) {
		ClientInfoContainerType::iterator j = i++;
		Client& client = dynamic_cast<Client&>(*j->second);
		EndPoint& endPoint = *client.connection;
		std::string data;
		while (true) {
			try {
				if (!endPoint.receivePacket(data)) {
					break;
				}
			} catch (...) {
				removeClient(j->first);
				break;
			}
			if (!data.empty()) {
				if (!handlePacket(client, data)) {
					removeClient(j->first);
					break;
				}
			}
		}
	}
	if (state == PLAY) {
		game->runUntil(clock.getTime(), std::bind(&Server::sendMessage, this, std::placeholders::_1));

		// PING
		Game::Message msg;
		msg.timestamp = game->getTime();
		sendMessage(msg);
	}
}
Exemple #22
0
void
RTMP::update()
{
    if (!connected()) {
        _handShaker->call();
        if (_handShaker->error()) {
            _error = true;
        }
        if (!_handShaker->success()) return;
        _connected = true;
    }
    
    const size_t reads = 10;

    for (size_t i = 0; i < reads; ++i) {

        /// No need to continue reading (though it should do no harm).
        if (error()) return;

        RTMPPacket p;

        // If we haven't finished reading a packet, retrieve it; otherwise
        // use an empty one.
        if (_incompletePacket.get()) {
            log_debug("Doing incomplete packet");
            p = *_incompletePacket;
            _incompletePacket.reset();
        }
        else {
            if (!readPacketHeader(p)) continue;
        }

        // Get the payload if possible.
        if (hasPayload(p) && !readPacketPayload(p)) {
            // If the payload is not completely readable, store it and
            // continue.
            _incompletePacket.reset(new RTMPPacket(p));
            continue;
        }
        
        // Store a copy of the packet for later additions and as a reference for
        // future sends.
        RTMPPacket& stored = storePacket(CHANNELS_IN, p.header.channel, p);
      
        // If the packet is complete, the stored packet no longer needs to
        // keep the data alive.
        if (isReady(p)) {
            clearPayload(stored);
            handlePacket(p);
            return;
        }
    }
}
void UDPServer::step()
{
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(m_fd, &fds);

    timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = 500 * 1000;

    int ret = select(m_fd + 1, &fds, 0, 0, &timeout);
    if(ret < 0)
    {
        // Silently ignore EINTR, EAGAIN
        if(errno == EINTR || errno == EAGAIN)
            return;

        errnoError("Could not select()");
    }

    if(ret > 0)
    {
        handlePacket();
    }

    // Cleanup old requestHandlers
    ros::Time now = ros::Time::now();

    auto it = m_requestList.begin();
    while(it != m_requestList.end())
    {
        auto& reqHandler = *it;

        if(now - reqHandler->receptionTime < ros::Duration(20.0))
            break;

        {
            boost::unique_lock<boost::mutex> lock(reqHandler->mutex);

            if(reqHandler->calling)
            {
                // This one is still active, keep it alive
                it++;
                continue;
            }

            reqHandler->serviceThread.join();
        }

        it = m_requestList.erase(it);
    }
}
Exemple #24
0
int UDPServer::run() {
	uint8_t* buf = nullptr;
	int len;
	string remoteAddr;

	while(!stop) {
		try {
			if(!socket->wait(400, true, false).first) {
				continue;
			}

			buf = new uint8_t[BUFSIZE];
			if((len = socket->read(buf, BUFSIZE, remoteAddr)) > 0) {
				pp.addTask([=] { handlePacket(buf, len, remoteAddr); });
				continue;
			}

			delete buf;
		} catch(const SocketException& e) {
			dcdebug("SearchManager::run Error: %s\n", e.getError().c_str());
		}

		bool failed = false;
		while(!stop) {
			try {
				socket->disconnect();
				port = socket->listen(Util::toString(CONNSETTING(UDP_PORT)));
				if(failed) {
					LogManager::getInstance()->message("Search enabled again", LogManager::LOG_INFO);
					failed = false;
				}
				break;
			} catch(const SocketException& e) {
				dcdebug("SearchManager::run Stopped listening: %s\n", e.getError().c_str());

				if(!failed) {
					LogManager::getInstance()->message(STRING_F(SEARCH_DISABLED_X, e.getError()), LogManager::LOG_ERROR);
					failed = true;
				}

				// Spin for 60 seconds
				for(auto i = 0; i < 60 && !stop; ++i) {
					Thread::sleep(1000);
				}
			}
		}
	}

	return 0;
}
Exemple #25
0
void PlayingState::handlePackets(Application & app)
{
	sf::TcpSocket & socket = app.getSocket();

	sf::Packet packet;
	sf::Socket::Status s = socket.receive(packet);

	while (s == sf::Socket::Done)
	{
		handlePacket(app, packet);
		packet.clear();
		s = socket.receive(packet);
	}
}
Exemple #26
0
void process_inbound_udp(int sock)
{
  #define BUFLEN 1500
  struct sockaddr_in from;
  socklen_t fromlen;
  char buf[BUFLEN];

  fromlen = sizeof(from);
  spiffy_recvfrom(sock, buf, BUFLEN, 0, (struct sockaddr *) &from, &fromlen);

  Packet *newPkt = newPacketFromBuffer(buf);
  memcpy(&(newPkt->src), &from, fromlen);
  handlePacket(newPkt);

}
bool Server::handlePacket() {
  sf::Packet in;

  for(auto &player : players){
     bool isT = isTurn(player->id);
     std::cout << "ID: " << player->id << "Is T: " << isT << std::endl;
     if (isTurn(player->id)) {
      if(player->socket.receive(in) == sf::Socket::Done ){
        std::cout << "got packet" << std::endl;
        return handlePacket(in, *player);
      }
    }
  }

  return true;
}
Exemple #28
0
void Game::netLoop()
{
	ENetEvent event;
	std::chrono::time_point<std::chrono::high_resolution_clock> tStart, tEnd;
	tStart = std::chrono::high_resolution_clock::now();
	long long tDiff;

	while(true)
	{
      while(enet_host_service(_server, & event, 0) > 0) {
         switch (event.type)
         {
         case ENET_EVENT_TYPE_CONNECT:
            //Logging->writeLine("A new client connected: %i.%i.%i.%i:%i \n", event.peer->address.host & 0xFF, (event.peer->address.host >> 8) & 0xFF, (event.peer->address.host >> 16) & 0xFF, (event.peer->address.host >> 24) & 0xFF, event.peer->address.port);

            /* Set some defaults */
            event.peer->mtu = PEER_MTU;
            event.data = 0;

            break;

         case ENET_EVENT_TYPE_RECEIVE:
            currentPeer = event.peer;
            if(!handlePacket(event.peer, event.packet,event.channelID))
            {
               //enet_peer_disconnect(event.peer, 0);
            }

            /* Clean up the packet now that we're done using it. */
            enet_packet_destroy (event.packet);
            break;

         case ENET_EVENT_TYPE_DISCONNECT:
            delete (ClientInfo*)event.peer->data;
            break;
         }
      }
      tEnd = tStart;
	   tStart = std::chrono::high_resolution_clock::now();
	   tDiff = std::chrono::duration_cast<std::chrono::microseconds>(tStart - tEnd).count();
      if(_started) {
         map->update(tDiff);
      }
      std::this_thread::sleep_for(std::chrono::microseconds(REFRESH_RATE*1000));
   }
}
 void Audio_Queue::handleAudioPackets(UInt32 inNumberBytes,
                                      UInt32 inNumberPackets,
                                      const void *inInputData,
                                      AudioStreamPacketDescription *inPacketDescriptions) {
     if (!initialized()) {
         AQ_TRACE("%s: warning: attempt to handle audio packets with uninitialized audio queue. return.\n", __PRETTY_FUNCTION__);
         
         return;
     }
     
     // this is called by audio file stream when it finds packets of audio
     AQ_TRACE("got data.  bytes: %u  packets: %u\n", inNumberBytes, (unsigned int)inNumberPackets);
     
     /* Place each packet into a buffer and then send each buffer into the audio
      queue */
     UInt32 i;
     
     for (i = 0; i < inNumberPackets && !m_waitingOnBuffer && m_queuedHead == NULL; i++) {
         AudioStreamPacketDescription *desc = &inPacketDescriptions[i];
         int ret = handlePacket((const char*)inInputData + desc->mStartOffset, desc);
         if (!ret) break;
     }
     if (i == inNumberPackets) {
         return;
     }
     
     for (; i < inNumberPackets; i++) {
         /* Allocate the packet */
         UInt32 size = inPacketDescriptions[i].mDataByteSize;
         queued_packet_t *packet = (queued_packet_t *)malloc(sizeof(queued_packet_t) + size);
         
         /* Prepare the packet */
         packet->next = NULL;
         packet->desc = inPacketDescriptions[i];
         packet->desc.mStartOffset = 0;
         memcpy(packet->data, (const char *)inInputData + inPacketDescriptions[i].mStartOffset,
                size);
         
         if (m_queuedHead == NULL) {
             m_queuedHead = m_queuedTail = packet;
         } else {
             m_queuedTail->next = packet;
             m_queuedTail = packet;
         }
     }
 }
/*------------------------------------------------------------------------------*/
void GRConnection::OnDataAvailable()
{
	GR_PACKET_HEADER pckHeader;
	GR_PACKET Packet;
	wxUint32 pos = 0;
	wxUint8 *payload;

	/* make sure we haven't deleted socket(Socket->Close() is delayed) */
	if(socket == NULL) return;

	/* read in header */
	socket->Read(&pckHeader, sizeof(pckHeader));

	/* endian conversion */
	pckHeader.command = ntohl(pckHeader.command);
	pckHeader.payloadLength = ntohl(pckHeader.payloadLength);

	/* read in payload */
	payload = new wxUint8[pckHeader.payloadLength];

	pos = 0;
	for(;;)
	{
		socket->Read(payload+pos, pckHeader.payloadLength-pos);
		pos += socket->LastCount();
		if(pos == pckHeader.payloadLength) break;
	}

	if(socket->Error()) 
	{
		GRLogger::getInstance()->log(GRLogger::LOG_ERROR, wxT("Error on socket. Not sure what to make out of it."));
	}

	/* put everything into our packet structure */
	Packet.header = &pckHeader;
	Packet.payload = payload;	


	GRLogger::getInstance()->log(GRLogger::LOG_INFO, wxString::Format(wxT("Command: %08X Payload Length: %d"), pckHeader.command, pckHeader.payloadLength));
	GRLogger::getInstance()->logData(Packet.payload, Packet.header->payloadLength);

	handlePacket(&Packet);

	delete[] payload;
}