//-------------------------------------------------------------------------------------
SDLNet_SocketSet GalactiCombatServer::createSockSet()
{
    if(verbose) std::cout << "Entering createSockSet" << std::endl;
    static SDLNet_SocketSet set = NULL;
    
    if(set) SDLNet_FreeSocketSet(set);
    set = SDLNet_AllocSocketSet(clients.size() + 1);
    if(!set)
    {
        std::cerr << "SDLNet_AllocSocketSet done goofed: " << SDLNet_GetError() << std::endl;
        exit(1);
    }
    SDLNet_TCP_AddSocket(set, TCPServerSock);
    for(int i = 0; i < clients.size(); i++)
        if(SDLNet_TCP_AddSocket(set, clients[i]->sock) == -1)
            std::cerr<<"SDLNet_TCP_AddSocket done goofed: "<<SDLNet_GetError()<<std::endl;
//	SDLNet_UDP_AddSocket(set, UDPServerSock);	//TODO: Uncomment when working on UDP.
    
    if(verbose) std::cout << "Exiting createSockSet" << std::endl << std::endl;
    return set;
}
Example #2
0
// Creates a socket set that has the server socket and all the client sockets
SDLNet_SocketSet Server::create_sockset()
{
    static SDLNet_SocketSet set = NULL;
    if(set)
        SDLNet_FreeSocketSet(set);
    set = SDLNet_AllocSocketSet(num_clients + 1);
    if(!set)
    {
        std::cerr << "SDLNet_AllocSocketSet: " << SDLNet_GetError()
                  << std::endl;
        return 0;
    }

    SDLNet_TCP_AddSocket(set, server);
    typedef std::map< std::string, TCPsocket >::iterator it_type;
    for (it_type i = clients.begin(); i != clients.end(); i++)
    {
        SDLNet_TCP_AddSocket(set, i->second);
    }
    return set;
}
Example #3
0
void TCPConnection::Close()
{
	logger->Log( __FILE__, __LINE__, "Closing connection.." );
	if ( !isConnected )
	{
		logger->Log( __FILE__, __LINE__, "Can't close : not connected" );
		return;
	}

	if ( isServer )
	{
		SDLNet_TCP_DelSocket( socketSet, serverSocket );
		SDLNet_TCP_Close( serverSocket );
		SDLNet_FreeSocketSet( socketSet );
	}
	else
	{
		SDLNet_TCP_Close( tcpSocket );
	}

	isConnected = false;
}
CHostSocket::CHostSocket( Uint32 port ) 
	: log("TcpSocketHost", CXmlSettings::Inst()->GetLoggerSettings()->logLevel)
{
	CIPAddress iplistener(port);
	if (!iplistener.ReadyForUse()) 
	{
		_socket = NULL;
		log << WARN << "IPaddress not ready for use" << endl;
	}
	else 
	{
		IPaddress ipHost = iplistener.GetIPAddress();
		if (!(_socket = SDLNet_TCP_Open(&ipHost))) 
		{
			SDLNet_FreeSocketSet(_socketSet);
			log << ERRORX << "SDLNet_TCP_Open: " << SDLNet_GetError() << endl;
		}
		else 
		{
			log << INFO << "Listening for clients on port: " << port << endl;
		}
	}

}
Example #5
0
void connect_to_server()
{
	IPaddress ip;
	if(this_version_is_invalid)return;
	if(set)
		{
			SDLNet_FreeSocketSet(set);
			set=0;
		}
	if(my_socket)
		{
			SDLNet_TCP_Close(my_socket);
			my_socket=0;
		}

	log_to_console(c_red1,connect_to_server_str);
	draw_scene();	// update the screen
	set=SDLNet_AllocSocketSet(1);
	if(!set)
        {
            char str[120];
            sprintf(str,"SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
            log_error(str);
			SDLNet_Quit();
			SDL_Quit();
			exit(4); //most of the time this is a major error, but do what you want.

        }

	if(SDLNet_ResolveHost(&ip,server_address,port)==-1)
		{
			log_to_console(c_red2,failed_resolve);
			return;
		}

	my_socket=SDLNet_TCP_Open(&ip);
	if(!my_socket)
		{
			//check to see if the player is a moron...
			if(server_address[0]=='1' && server_address[1]=='9' && server_address[2]=='2'
			   && server_address[3]=='.' && server_address[4]=='1' && server_address[5]=='6'
			   && server_address[6]=='8')
			  	{
			   		log_to_console(c_red1,license_check);
					log_to_console(c_red1,alt_x_quit);
				}
			else
				{
					log_to_console(c_red1,failed_connect);
					log_to_console(c_red1,reconnect_str);
					log_to_console(c_red1,alt_x_quit);
				}
            return;
		}

	if(SDLNet_TCP_AddSocket(set,my_socket)==-1)
		{
            char str[120];
            sprintf(str,"SDLNet_TCP_AddSocket: %s\n",SDLNet_GetError());
            log_error(str);
			SDLNet_Quit();
			SDL_Quit();
			exit(2);
		}
	disconnected=0;
	//ask for the opening screen
	if(!previously_logged_in)
		{
			Uint8 str[1];
			str[0]=SEND_OPENING_SCREEN;
			my_tcp_send(my_socket,str,1);
		}
	else
		{
			yourself=-1;
			you_sit=0;
			destroy_all_actors();
			send_login_info();
		}

    //send the current version to the server
    send_version_to_server(&ip);
    last_heart_beat=cur_time;
	hide_window(trade_win);
}
Example #6
0
ClientConnection::~ClientConnection() {
	SDLNet_TCP_Close(_client_socket);
	SDLNet_FreeSocketSet(_socket_set);
}
Example #7
0
 TCP_Socket::~TCP_Socket() {
   SDLNet_TCP_DelSocket(sockset, sock);
   SDLNet_FreeSocketSet(sockset);
   SDLNet_TCP_Close(sock);
 }
Example #8
0
static __inline__ void snFreeSocketSet(SDLNet_SocketSet ss)
{
  lockSDLNet();
  SDLNet_FreeSocketSet(ss);
  unlockSDLNet();
}
Example #9
0
void TcpNet::freeSocketSet(const TcpNet::SocketSet set)
{
    SDLNet_FreeSocketSet(set);
}
Example #10
0
void Server::startListen(ConnectionData * data){
	int ready = 0;
	TCPsocket newSocket = NULL;
	SDLNet_SocketSet set = NULL;
	Client* newClient = NULL;

	set = SDLNet_AllocSocketSet(1);
	if(!set) {
		std::cerr << "SDLNet_AllocSocketSet: " << SDLNet_GetError() << std::endl;
		exit(0);
	}
	SDLNet_TCP_AddSocket(set, data->socket);

	if(myMapManager->loadXMLMap(MAP_TESTING)){
		std::ostringstream tmp;
		tmp << "Loaded XML Map -> " << MAP_TESTING << ".xml";
		myConsole.printMsg(tmp);
	}
	else{
		std::ostringstream tmp;
		tmp << "Failed to load Map -> " << MAP_TESTING << ".xml";
		myConsole.printMsg(tmp, CONSOLE_ERROR);
		return;
	}
	
	if(myMapManager->loadBinTMap(MAP_T)){
		std::ostringstream tmp;
		tmp << "Loaded Terrain Map -> " << MAP_T;
		myConsole.printMsg(tmp);
	}
	else{
		std::ostringstream tmp;
		tmp << "Failed to load Map -> " << MAP_T;
		myConsole.printMsg(tmp, CONSOLE_ERROR);
		return;
	}	
	
	myGamefsm.Start(); // Starts the game state machine.

	while(!initialized){ // Wait for the server to be initialized
		SDL_Delay(100);
	}

	// Now the server is up and running, inform the user.
	myConsole.printMsg("Server is now running!");

	// Main server loop. Here we accept new connections.
	while(!exit_request){
		ready = SDLNet_CheckSockets(set, (Uint32) 50);
		if(ready==-1){
			std::cout << "SDLNet_CheckSockets: " << SDLNet_GetError() << std::endl;
			break;
		}
		if(!ready)
			continue;
		if(SDLNet_SocketReady(data->socket)){
			newSocket=SDLNet_TCP_Accept(data->socket);
			if (newSocket){
				newClient = new Client(newSocket, this);
				//addClient(newClient);
				#ifdef TESTPHASE
				myConsole.printMsg("Connection received, authenticating it...");
				//std::cout << std::endl << "<Server> Now " << this->mClients.size() << " clients are connected." << std::endl;
				#endif
			}
		}
	}

	SDLNet_FreeSocketSet(set);
	// Since the server is exiting do the same with the game FSM.
	myGamefsm.Stop();
	SDL_Thread* tmpThread = myGamefsm.getThread();
	if (tmpThread != NULL) // If necessary wait for the GameFSM to finish.
        SDL_WaitThread(tmpThread, NULL);

	myConsole.printMsg("Server is now quitting, good bye!");

}
Example #11
0
//-----------------------------------------------------------------------------
int main(int argc, char** argv) {
	if(SDL_Init(SDL_INIT_TIMER|SDL_INIT_EVENTS) != 0) {
		fprintf(stderr, "ER: SDL_Init: %s\n", SDL_GetError());
		exit(-1);
	}

	if(SDLNet_Init() == -1) {
		fprintf(stderr, "ER: SDLNet_Init: %s\n", SDLNet_GetError());
		exit(-1);
	}

	IPaddress ip;
	if(SDLNet_ResolveHost(&ip, NULL, 8099) == -1) {
		fprintf(stderr, "ER: SDLNet_ResolveHost: %s\n", SDLNet_GetError());
		exit(-1);
	}

	sockets[SERVER_SOCKET] = SDLNet_TCP_Open(&ip);
	if(sockets[SERVER_SOCKET] == NULL) {
		fprintf(stderr, "ER: SDLNet_TCP_Open: %s\n", SDLNet_GetError());
		exit(-1);
	}

	socket_set = SDLNet_AllocSocketSet(MAX_SOCKETS);
	if(socket_set == NULL) {
		fprintf(stderr, "ER: SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
		exit(-1);
	}

	if(SDLNet_TCP_AddSocket(socket_set, sockets[SERVER_SOCKET]) == -1) {
		fprintf(stderr, "ER: SDLNet_TCP_AddSocket: %s\n", SDLNet_GetError());
		exit(-1);
	}

	int running = 1;
	while(running) {
		int num_rdy = SDLNet_CheckSockets(socket_set, 1000);

		if(num_rdy <= 0) {
			// NOTE: none of the sockets are ready
			int ind;
			for(ind=0; ind<MAX_SOCKETS; ++ind) {
				if(!clients[ind].in_use) continue;

				/*
				if(clients[ind].questing &&
					(SDL_GetTicks()-clients[ind].timer_wood)>WOOD_WAIT_TIME
				) {
					
					clients[ind].questing = 0;
					clients[ind].amt_wood += 4;
					char msg[0xFF] = "> quest complete\n\r";
					SendData(ind, msg, (strlen(msg)+1));
					
				}
				*/

				clients[ind].amt_wood += 4;

				/*
				uint16_t length = 0;
				uint8_t data[MAX_PACKET];

				memcpy(data+length, &clients[ind].amt_wood, sizeof(uint8_t));
				length += sizeof(uint8_t);

				SendData(ind, data, length, FLAG_WOOD_UPDATE);
				*/
			}
		} else {
			int ind;
			for(ind=0; (ind<MAX_SOCKETS) && num_rdy; ++ind) {
				if(sockets[ind] == NULL) continue;
				if(!SDLNet_SocketReady(sockets[ind])) continue;

				if(ind == SERVER_SOCKET) {
					int got_socket = AcceptSocket(next_ind);
					if(!got_socket) {
						num_rdy--;
						continue;
					}

					// NOTE: get a new index
					int chk_count;
					for(chk_count=0; chk_count<MAX_SOCKETS; ++chk_count) {
						if(sockets[(next_ind+chk_count)%MAX_SOCKETS] == NULL) break;
					}

					next_ind = (next_ind+chk_count)%MAX_SOCKETS;
					printf("DB: new connection (next_ind = %d)\n", next_ind);

					num_rdy--;
				} else {
					uint8_t* data;
					uint16_t flag;
					uint16_t length;
					
					data = RecvData(ind, &length, &flag);
					if(data == NULL) {
						num_rdy--;
						continue;
					}

					switch(flag) {
						case FLAG_WOOD_UPDATE: {
							uint16_t offset = 0;
							uint8_t send_data[MAX_PACKET];

							memcpy(send_data+offset, &clients[ind].amt_wood, sizeof(uint8_t));
							offset += sizeof(uint8_t);

							SendData(ind, send_data, offset, FLAG_WOOD_UPDATE);
						} break;
					}

					/*
					uint8_t* data; int length;

					data = RecvData(ind, &length);
					if(data == NULL) {
						num_rdy--;
						continue;
					}

					int i;
					for(i=0; i<length; ++i) {
						if(data[i] == '\n') data[i] = '\0';
						if(data[i] == '\r') data[i] = '\0';
					}

					// TEMP: add a NULL terminator
					data = (uint8_t*) realloc(data, (length+1));
					data[length] = '\0';

					int was_processed = 0;
					if(!strcmp(data, "exit")) {

						was_processed = 1;
						running = 0;

					} else if(!strcmp(data, "quit")) {

						was_processed = 1;
						CloseSocket(ind);

					} else if(!strcmp(data, "get data")) {

						was_processed = 1;
						char msg[0xFF] = {};
						sprintf(msg, "> wood: %d\n\r", clients[ind].amt_wood);
						//SendData(ind, msg, (strlen(msg)+1));

					} else if(!strcmp(data, "quest")) {

						was_processed = 1;
						if(!clients[ind].questing) {
							clients[ind].questing = 1;
							clients[ind].timer_wood = SDL_GetTicks();
							char msg[0xFF] = "> started quest\n\r";
							//SendData(ind, msg, (strlen(msg)+1));
						} else {
							char msg[0xFF] = "> currently running quest\n\r";
							//SendData(ind, msg, (strlen(msg)+1));
						}

					}

					if(was_processed) printf("PR: %s\n", data);
					free(data);
					*/

					num_rdy--;
				}
			}
		}
	}

	int i;
	for(i=0; i<MAX_SOCKETS; ++i) {
		if(sockets[i] == NULL) continue;
		CloseSocket(i);
	}

	SDLNet_FreeSocketSet(socket_set);
	SDLNet_Quit();
	SDL_Quit();

	return 0;
}
Example #12
0
/*!
 * main loop. Accept contribution from clients and dispatch digest of
 * the frame to all clients
 */
void
serve_dispatch (global_option_type * global_option)
{

  global_status_type global_status;
  int client_index;

  /*
   * Initialize global_status fields
   */
  global_status.frame_number = 1;
  global_status.number_identified_players = 0;
  global_status.number_allocation_request = 0;
#if defined(GTK)
	gtk_stop_asked = 0;
#endif

  for (client_index = 0; client_index < MAX_NUMBER_PLAYER; client_index++)
    {
      global_status.player_status[client_index] = UNIDENTIFIED;
    }

  global_status.server_socket = SDLNet_UDP_Open (global_option->server_port);
  if (global_status.server_socket == NULL)
    {
      printf_screen ("Couldn't open UDP socket on port %d.\nCheck privileges and availability.\n",
		     global_option->server_port);
      return;
    }

  /* global_status.server_socket is ready to serve our needs :) */

  global_status.current_packet = SDLNet_AllocPacket (CLIENT_PACKET_SIZE);

  if (global_status.current_packet == NULL)
    {
      SDLNet_UDP_Close (global_status.server_socket);
      printf_screen ("Failed to allocate a buffer for receiving client packets (size: %d bytes) (Not enough memory ?)",
		     CLIENT_PACKET_SIZE);
      return;
    }

  global_status.digest_packet = SDLNet_AllocPacket (SERVER_PACKET_SIZE);

  if (global_status.digest_packet == NULL)
    {
      SDLNet_UDP_Close (global_status.server_socket);
      SDLNet_FreePacket (global_status.digest_packet);
      printf_screen ("Failed to allocate a buffer for sending packets (size: %d bytes) (Not enough memory ?)",
		     SERVER_PACKET_SIZE);
      return;
    }

  /* Allocate enough space for a single socket */
  global_status.server_socket_set = SDLNet_AllocSocketSet (1);

  if (global_status.server_socket_set == NULL)
    {
      SDLNet_UDP_Close (global_status.server_socket);
      SDLNet_FreePacket (global_status.current_packet);
      SDLNet_FreePacket (global_status.digest_packet);
      printf_screen ("Couldn't allocate a socket set (not enough memory ?).\n");
      return;
    }

  if (SDLNet_UDP_AddSocket (global_status.server_socket_set, global_status.server_socket) !=
      1)
    {
      SDLNet_UDP_Close (global_status.server_socket);
      SDLNet_FreePacket (global_status.current_packet);
      SDLNet_FreePacket (global_status.digest_packet);
      SDLNet_FreeSocketSet (global_status.server_socket_set);
      printf_screen ("Error when adding socket to socket set.\n");
      return;
    }

  /* Identification loop */

  /*
   * We're expecting identification packets until we've filled all slots, then
   * we can proceed to the real meat
   */

  for (;;)
    {

      int number_ready_socket;

#if defined(DEBUG)
      printf_screen ("Waiting for identification\n");
#endif

      
      if (read_incoming_server_packet (&global_status))
	{
	  identify_client (&global_status, global_option);
	  
	  if (count_remaining_slot (&global_status, global_option) == 0)
	    {
	      /* Perfect, we've finished the identification of all slots */
	      break;
	    }
	  
	  printf_screen("%d slots open.\n", count_remaining_slot (&global_status, global_option));
	  
	  /* Going back to the identification loop */
	  continue;
	  
	}

#if defined(GTK)

      gtk_iteration = GTK_SERVER_SOCKET_RATIO;

      do {
	number_ready_socket =
	  SDLNet_CheckSockets (global_status.server_socket_set, SERVER_SOCKET_TIMEOUT / GTK_SERVER_SOCKET_RATIO);
	  
	while (gtk_events_pending())
	{
	  if (gtk_main_iteration())
	  {
	  	gtk_stop_asked = 1;
	  }
	}
      } while ( (number_ready_socket == 0) && (--gtk_iteration != 0) && !gtk_stop_asked);
#else

      number_ready_socket =
	SDLNet_CheckSockets (global_status.server_socket_set, SERVER_SOCKET_TIMEOUT);      

#endif

	if (gtk_stop_asked)
	{
		break;
	}

      if (number_ready_socket == -1)
	{
	  printf_screen ("Error in socket waiting (disconnection ?).\n");
	  break;
	}

      if (number_ready_socket == 1)
	{

#if defined(DEBUG)
	  printf_screen ("Got a packet\n");
#endif

	  /* We're awaiting a packet in the server socket */
	  if (read_incoming_server_packet (&global_status))
	    {

	      /*
	       * If we haven't identified all clients yet, we're trying to use the current packet
	       * to improve our knowledge of the typography
	       */
	      identify_client (&global_status, global_option);
	      
	      if (count_remaining_slot (&global_status, global_option) == 0)
		{
		  /* Perfect, we've finished the identification of all slots */
		  break;
		}

	      printf_screen("%d slots open.\n", count_remaining_slot (&global_status, global_option));

	    }
    }

	
	}

	if (!gtk_stop_asked)
	{

  printf_screen ("Identification finished\n");

#if defined(DEBUG)
  for (client_index = 0; client_index < MAX_NUMBER_PLAYER; client_index++)
    {
      printf_screen ("Mapping[%d] = { { 0x%08X, %d }, %d }\n", client_index,
		     global_status.input_mapping[client_index].address.host,
		     global_status.input_mapping[client_index].address.port,
		     global_status.input_mapping[client_index].remote_input_device);
    }
#endif

  switch (global_option->type_server)
    {
    case LAN_PROTOCOL_TYPE:
      serve_clients_lan_protocol(&global_status, global_option);
      break;
    case INTERNET_PROTOCOL_TYPE:
      serve_clients_internet_protocol(&global_status, global_option);
      break;
    default:
      printf_screen("Internal error, unknown internal server type : %d\n", global_option->type_server);
      break;
    }
  } // gtk_stop_asked
      
  /*
   * Free resources
   */
  SDLNet_FreePacket (global_status.current_packet);
  SDLNet_FreePacket (global_status.digest_packet);
  SDLNet_FreeSocketSet (global_status.server_socket_set);
  SDLNet_UDP_Close (global_status.server_socket);
  global_status.server_socket = NULL;

}
Example #13
0
void Network::receive()
{
    SDLNet_SocketSet set;

    if (!(set = SDLNet_AllocSocketSet(1)))
    {
        setError("Error in SDLNet_AllocSocketSet(): " +
            std::string(SDLNet_GetError()));
        return;
    }

    if (SDLNet_TCP_AddSocket(set, mSocket) == -1)
    {
        setError("Error in SDLNet_AddSocket(): " +
            std::string(SDLNet_GetError()));
    }

    while (mState == CONNECTED)
    {
        // TODO Try to get this to block all the time while still being able
        // to escape the loop
        int numReady = SDLNet_CheckSockets(set, (static_cast<uint32_t>(500)));
        int ret;
        switch (numReady)
        {
            case -1:
                logger->log1("Error: SDLNet_CheckSockets");
                // FALLTHROUGH
            case 0:
                break;

            case 1:
                // Receive data from the socket
                SDL_mutexP(mMutex);
                ret = SDLNet_TCP_Recv(mSocket, mInBuffer + mInSize,
                                      BUFFER_SIZE - mInSize);

                if (!ret)
                {
                    // We got disconnected
                    mState = IDLE;
                    logger->log1("Disconnected.");
                }
                else if (ret < 0)
                {
                    setError(_("Connection to server terminated. ") +
                             std::string(SDLNet_GetError()));
                }
                else
                {
//                    DEBUGLOG("Receive " + toString(ret) + " bytes");
                    mInSize += ret;
                    if (mToSkip)
                    {
                        if (mInSize >= mToSkip)
                        {
                            mInSize -= mToSkip;
                            memmove(mInBuffer, mInBuffer + mToSkip, mInSize);
                            mToSkip = 0;
                        }
                        else
                        {
                            mToSkip -= mInSize;
                            mInSize = 0;
                        }
                    }
                }
                SDL_mutexV(mMutex);
                break;

            default:
                // more than one socket is ready..
                // this should not happen since we only listen once socket.
                std::stringstream errorStream;
                errorStream << "Error in SDLNet_TCP_Recv(), " << numReady
                            << " sockets are ready: " << SDLNet_GetError();
                setError(errorStream.str());
                break;
        }
    }

    if (SDLNet_TCP_DelSocket(set, mSocket) == -1)
        logger->log("Error in SDLNet_DelSocket(): %s", SDLNet_GetError());

    SDLNet_FreeSocketSet(set);
}
Example #14
0
//-----------------------------------------------------------------------------
int main(int argc, char *argv[]) {
	libInit();

	// NOTE: open socket file descriptor
	serverFD = SDLNet_UDP_Open(3490);
	if(!serverFD) {
		fprintf(stderr, "SDLNet_UDP_Open: %s\n", SDLNet_GetError());
		libQuit();
		return -1;
	}

	// NOTE: setup a socket set
	socketSet = SDLNet_AllocSocketSet(1);
	SDLNet_UDP_AddSocket(socketSet, serverFD);
	printf("\nServer open on port: %d\n\n", 3490);

	// NOTE: initialize the player manager
	plManager = initPlayerManager("diamond_collector.db");

	/*
		LISTEN FOR PACKETS
	*/

	for(;;) {
		// NOTE: wait for a connection
		int n = SDLNet_CheckSockets(socketSet, 0);

		if(n==-1) {
			fprintf(stderr, "SDLNet_CheckSockets: %s\n", SDLNet_GetError());
			break;
		} if(!n) {
			// NOTE: if the server doesn't have anything to do then run through
			// a few regular routines
			switch(serverState) {
				case 0x00: {
					if((time(NULL)-lastTimePingsWentOut)>20) {
						// NOTE: if the server is idle in its freetime then start sending out
						// ping packets for the client to respond to
						serverState = 0x01;
						lastTimePingsWentOut = time(NULL);
					}
				} break;
				case 0x01: {
					if(waitingForPong) {
						if(!plManager->pl_indMask[nodeToPing][playerToPing]) {
							playerToPing++;
							waitingForPong = SDL_FALSE;
						} else if((time(NULL)-timeOfPing)>120) {
							// NOTE: if we hear nothing back after 5 secs then disconnect the player
							DB_Player *pl = &plManager->pl_dbInfo[nodeToPing][playerToPing];
							printf("player %s didn't respond to ping logging them out.\n", pl->username);

							// NOTE: set the player state and log the player out
							pl->state = 0x00;

							// NOTE: send a packet out to everyone on this node
							// letting them know that the player is leaving.
							UDPpacket _packet = {};

							/*
							- flag (1) 0x05
							- id   (4)
							====== (5)
							*/

							_packet.maxlen = 0x05; // 5 bytes
							_packet.data = (uint8_t *)malloc(0x05);

							uint8_t offset = 0;

							memset(_packet.data+offset, 0x05, 1);
							offset += 1;
							memcpy(_packet.data+offset, &pl->id, 4);
							offset += 4;

							// NOTE: set the packet length to the offset point
							_packet.len = offset;

							// NOTE: send the packet out to everyone but the player disconnecting
							int i;
							for(i=0; i<PLAYER_MAX; i++) {
								if(!plManager->pl_indMask[pl->node][i])
									continue;

								_packet.address.host = plManager->pl_dbInfo[pl->node][i].host;
								_packet.address.port = plManager->pl_dbInfo[pl->node][i].port;

								if(!SDLNet_UDP_Send(serverFD, -1, &_packet))
									fprintf(stderr, "SDLNet_UDP_Send: %s\n", SDLNet_GetError());
							}

							// NOTE: free the packet
							free(_packet.data);

							// NOTE: save the new player state
							pl_save(plManager, pl);

							if(pl_removePlayer(plManager, pl) != -1) {
								printf("Logout success!\n");
							} else {
								// NOTE: player was never in the players array should
								// probably log this sort of thing
							}

							playerToPing++;
							waitingForPong = SDL_FALSE;
						} else {
							// TODO: keep sending the ping packet
						}
					} else {
						// NOTE: make sure there are people on this node - else go to the
						// next node
						int n = pl_numOnNode(plManager, nodeToPing);

						if(n <= 0) {
							nodeToPing++;
							playerToPing = 0;

							if(nodeToPing==NODE_MAX) {
								nodeToPing = 0;
								serverState = 0x00;
							}

							break;
						}

						// NOTE: if there isn't a player at this point in the pool then
						// go to the next point in the pool
						if(!plManager->pl_indMask[nodeToPing][playerToPing]) {
							playerToPing++;

							if(playerToPing == PLAYER_MAX) {

								nodeToPing++;
								playerToPing = 0;

								if(nodeToPing == NODE_MAX) {
									nodeToPing = 0;
									serverState = 0x00;
								}
							}

							break;
						}

						// NOTE: get the player and send out the ping
						DB_Player *pl = &plManager->pl_dbInfo[nodeToPing][playerToPing];

						// NOTE: send a ping packet
						uint8_t flag = 0x0A;
						UDPpacket _packet = {};

						_packet.data = &flag;

						_packet.len = 1;
						_packet.maxlen = 1;

						_packet.address.host = pl->host;
						_packet.address.port = pl->port;

						if(!SDLNet_UDP_Send(serverFD, -1, &_packet))
							fprintf(stderr, "SDLNet_UDP_Send: %s\n", SDLNet_GetError());

						timeOfPing = time(NULL);
						waitingForPong = SDL_TRUE;
					}
				} break;
			}
			continue;
		}

		// NOTE: does the server have packets waiting?
		if(SDLNet_SocketReady(serverFD)) {
			// NOTE: setup a packet which is big enough to store any client message
			UDPpacket packet;

			// NOTE: allocate space for packet
			packet.maxlen = 0xAA; // 170 bytes
			packet.data = (uint8_t *)malloc(0xAA);

			// NOTE: get the packet
			int recv = SDLNet_UDP_Recv(serverFD, &packet);
			if(!recv) {
				free(packet.data);
				continue;
			}

			// NOTE: read the flag for packet identity
			uint8_t flag = 0;
			uint32_t offset = 0;

			memcpy(&flag, packet.data, 1);
			offset += 1;

			// NOTE: process the packet
			switch(flag) {
				case 0x01: {

					net_login(plManager, &packet, &offset);

				} break;
				case 0x02: {
					
					net_logout(plManager, &packet, &offset);

				} break;
				case 0x07: {
					
					net_moveUp(plManager, &packet, &offset);

				} break;
				case 0x08: {
					
					net_moveDown(plManager, &packet, &offset);

				} break;
				case 0x09: {
					
					net_moveLeft(plManager, &packet, &offset);

				} break;
				case 0x0A: {
					
					net_moveRight(plManager, &packet, &offset);

				} break;
				case 0x0B: {

					net_sendOutPlInfo(plManager, &packet, &offset);
					
				} break;
				case 0x0C: {
					// NOTE: get the player which is logged in on the incoming address
					DB_Player *pl = pl_getDBInfo(plManager, packet.address);
					if(pl == NULL) break;

					// NOTE: need to make sure the pong is from the right player
					int ind = pl_getIndex(plManager, pl);

					// NOTE: player responding with a pong packet
					if(ind==playerToPing) {
						playerToPing++;
						waitingForPong = SDL_FALSE;
					}
				} break;
				case 0x0D: {
					
					net_sendOutNodeInfo(plManager, &packet, &offset);

				} break;
			}

			// NOTE: free the packet when done processing
			free(packet.data);
		}
	}

	// NOTE: free the player manager
	freePlayerManager(plManager);

	// NOTE: free socketset
	SDLNet_FreeSocketSet(socketSet);

	// NOTE: close the socket file descriptor
	SDLNet_UDP_Close(serverFD);

	libQuit();

	return 0;
}
Example #15
0
Socket::~Socket() {
    SDLNet_TCP_Close(sock);
    if (set != NULL)
        SDLNet_FreeSocketSet(set);
}