Exemplo n.º 1
0
int load_empty_map()
{
	if (!el_load_map("./maps/nomap.elm"))
	{
#ifndef MAP_EDITOR2
		locked_to_console = 1;
		hide_window (game_root_win);
		show_window (console_root_win);
		LOG_TO_CONSOLE(c_red4, no_nomap_str);
		LOG_ERROR(cant_change_map, "./maps/nomap.elm");
		SDLNet_TCP_Close(my_socket);
		disconnected = 1;
#ifdef NEW_SOUND
		stop_all_sounds();
#endif // NEW_SOUND
		disconnect_time = SDL_GetTicks();
		SDLNet_Quit();
		LOG_TO_CONSOLE(c_red3, disconnected_from_server);
		//Fake a map to make sure we don't get any crashes.
#endif
		safe_snprintf(map_file_name, sizeof(map_file_name), "./maps/nomap.elm");
		tile_map_size_y = 256;
		tile_map_size_x = 256;
		dungeon = 0;
		ambient_r = 0;
		ambient_g = 0;
		ambient_b = 0;
		tile_map = calloc(tile_map_size_x*tile_map_size_y, sizeof(unsigned char));
		height_map = calloc(tile_map_size_x*tile_map_size_y*6*6, sizeof(unsigned char));
#ifndef MAP_EDITOR2
		pf_tile_map = calloc(tile_map_size_x*tile_map_size_y*6*6, sizeof(PF_TILE));
#endif
		return 0;
	}
	return 1;
}
Exemplo n.º 2
0
int
main(int argc, char *argv[])
{
   SDL_Window  *window;
   CLC_CONFIG  config;
   Uint8       *kbdstate;
   SDL_Event   e;
   PLAYER      *me;
   PLAYER      *player;
   Uint32      time;
   IPaddress   srv_ip;
   TCPsocket   srv_sock;
   Uint16      magic;
   int         i;
   SDLNet_SocketSet srv_sset;
   char myname[PNAME_SIZE];
   unsigned char myno;

   if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_EVENTS) == -1)
   {
      fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
      exit(EXIT_FAILURE);
   }

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

   parsecfg(&config);

   /*
    * Get player name.
    */
   printf("Wow such name: ");
   fgets(myname, PNAME_SIZE, stdin);

   for (i = 0; i < PNAME_SIZE; i++)
   {
      if (myname[i] == '\n')
      {
         myname[i] = '\0';
         break;
      }
   }


   /*
    * Connect to server!
    */
   if (SDLNet_ResolveHost(&srv_ip, config.defaultsrv,
            atoi(config.defaultport)))
   {
      fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
      exit(EXIT_FAILURE);
   }


   /*
    * Bind socket!
    */
   if (!(srv_sock = SDLNet_TCP_Open(&srv_ip)))
   {
      fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
      exit(EXIT_FAILURE);
   }


   /*
    * Add (a single) server socket to srv_sset for cheap hack for checking
    * the server socket's state.
    */
   srv_sset = SDLNet_AllocSocketSet(1);

   if (!srv_sset)
   {
      printf("SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
      exit(EXIT_FAILURE);
   }

   SDLNet_TCP_AddSocket(srv_sset, srv_sock);


   /*
    * Get maze, add connecting players to buffer and wait until the game
    * begins.
    */

   getmaze(srv_sock);

   window = SDL_CreateWindow(
         "MAZE OF TORMENT",
         SDL_WINDOWPOS_UNDEFINED,
         SDL_WINDOWPOS_UNDEFINED,
         config.win_width,
         config.win_height,
         config.win_flags
   );

   SDL_GetWindowSize(window, &config.win_width, &config.win_height);

   if (window == NULL)
   {
      fprintf(stderr, "Could not create window: %s\n",
            SDL_GetError());
      exit(EXIT_FAILURE);
   }

   renderer = SDL_CreateRenderer(window, -1, config.renderflags);

   hsprite  = loadPic("img/predator.gif");
   psprite  = loadPic("img/prey.gif");
   black    = loadPic("img/black.gif");

   /*
    * Initialize maze, and send player name.
    */
   MAZE.X = (config.win_width - MAZE.w * 16) / 2;
   MAZE.Y = (config.win_height - MAZE.h * 16) / 2;

   SDLNet_TCP_Send(srv_sock, myname, PNAME_SIZE);


   /*
    * Initialize maze and get the LOCAL player, then the REMOTE players.
    */

   SDLNet_TCP_Recv(srv_sock, &myno, 1);
   player = calloc(1, sizeof(PLAYER));

   if (!((magic = getshort(srv_sock)) == ADD_PLAYER))
   {
      printf("server not sending players\n!");
      exit(EXIT_FAILURE);
   }

   unsigned char hunter = addp(player, srv_sock);

   choose_hunter(player, hunter);
   me = choose_player(player, myno);

   SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
   draw_maze(MAZE.X, MAZE.Y);

   PLAYER *temp;

   for (temp = player->next; temp != NULL; temp = temp->next)
   {
      printf("drew player %d\n", temp->playerno);
      drawPlayer(temp);
   }
   
   printf("starting game!!\n");
   /*
    * Game loop!
    */
   
   for (;;)
   {
      time = SDL_GetTicks();

      /*
       * Poll the  network in each frame. Because.
       */

      int result, numready = SDLNet_CheckSockets(srv_sset, 0);

      if (numready == -1)
      {
         printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError());
         perror("SDLNet_CheckSockets");
      }
      else if (numready)
      {
         unsigned char packet;
         unsigned char pnum, movx, movy;

         printf("srv socket is ready!!\n");

         if ((result = SDLNet_TCP_Recv(srv_sock, &packet, 2)) == 2)
         {
            switch (SDLNet_Read16(&packet))
            {
               case PLAYER_MOV:
                  puts("PLAYER_MOV");
                  pnum = getshort(srv_sock);
                  movx = getshort(srv_sock);
                  movy = getshort(srv_sock);

                  printf("player %d moved to (%d,%d)\n",
                              pnum, movx, movy);
                  movePlayer(choose_player(player,pnum), movx, movy);
                  break;

               case PLAYER_WIN:
                  puts("PLAYER_WIN");
                  break;

               case PLAYER_DC:
                  puts("PLAYER_DC");
                  pnum = getshort(srv_sock);
                  printf("Player %d disconnected!!\n", pnum);
                  removep(choose_player(player,pnum));
                  break;

               case PLAYER_DIE:
                  puts("PLAYER_DIE");
                  pnum = getshort(srv_sock);

                  if (pnum == myno)
                  {
                     puts("YOU ARE DEAD\nGAME OVER");
                     goto exit;
                  }
                  printf("Player %d deaded!!!!!\n", pnum);
                  removep(choose_player(player, pnum));
                  break;

            }
         }
         else if (result <= 0)
         {
            fprintf(stderr, "SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
            fprintf(stderr, "Lost connection to the server?\n");
            break;
         }
      }

      /*
       * Poll for keys
       */
      if (SDL_PollEvent(&e))
      {
         if (e.type == SDL_QUIT)
         {
            break;
         }

         kbdstate = (Uint8 *) SDL_GetKeyboardState(NULL);

         if (kbdstate[SDL_SCANCODE_Q])
         {
            break;
         }

         local_player_update(srv_sock, me, player, SDL_GetKeyboardState(NULL));
      }

      SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
      SDL_RenderPresent(renderer);

      if (20 > (SDL_GetTicks() - time))
      {
         SDL_Delay(20 - (SDL_GetTicks() - time));
      }
   }

exit:
   SDL_DestroyTexture(psprite.texture);
   SDL_DestroyTexture(hsprite.texture);
   SDL_DestroyTexture(black.texture);
   free(player);
   free(MAZE.data);

   SDL_DestroyWindow(window);

   SDLNet_Quit();
   SDL_Quit();

   return 0;
}
Exemplo n.º 3
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);
}
Exemplo n.º 4
0
// Main app
int main(int argc, char **argv)
{
	// SDL 
	IPaddress ip,*remoteip;
	TCPsocket server,client;
	Uint32 ipaddr;

	// Bool to represent mode of execution
	bool bHCAMMode = false;
	
	// initialize SDL
	if(SDL_Init(0)==-1)
	{
		printf("SDL_Init: %s\n",SDL_GetError());
		exit(1);
	}

	// initialize SDL_net
	if(SDLNet_Init()==-1)
	{
		printf("SDLNet_Init: %s\n",SDLNet_GetError());
		exit(2);
	}
	
	// Read arguments from command line
	int nargs_set = 0;
	std::string camhost, camuser, campass, move;
	int proxyport, camport;
	unsigned short camID = 1;

	// Hardcoded defaults
	proxyport = 8888;
	camport = 9001;

	int i =0;
	for(i=0; i < argc; i++)
	{
		if( strcmp(argv[i],"-camid") == 0)
		{
			if (++i >= argc) {
			  display_usage();
			  return 0;
			};
			camID = atoi(argv[i]);

			// Do not increment nargs_set as we default this option to cam 1
		}
		else if( strcmp(argv[i],"-camhost") == 0 ) 
		{
			if (++i >= argc) {
			  display_usage();
			  return 0;
			};
			camhost = argv[i];
			++nargs_set;
		}
		else if( strcmp(argv[i],"-camport") == 0 )
		{
			if (++i >= argc) {
			  display_usage();
			  return 0;
			};
			camport = atoi(argv[i]);
			++nargs_set;
		}
		else if( strcmp(argv[i], "-proxyport") == 0 )
		{
			if (++i >= argc) {
			  display_usage();
			  return 0;
			};
			proxyport = atoi(argv[i]);
			++nargs_set;
		}
		else if( strcmp(argv[i],"-camuser") == 0 )
		{
			if (++i >= argc) {
			  display_usage();
			  return 0;
			};
			camuser = argv[i];
			++nargs_set;
		}
		else if( strcmp(argv[i],"-campass") == 0 )
		{
			if (++i >= argc) {
			  display_usage();
			  return 0;
			};
			campass = argv[i];
			++nargs_set;
		}
		else if(strcmp(argv[i],"-HCAMV") == 0 )
		{
			bHCAMMode = true;
			++nargs_set; 
		}
		else if( strcmp(argv[i],"-move") == 0 )
		{
			if (++i >= argc) {
			  display_usage();
			  return 0;
			};
			move = argv[i];
			++nargs_set; 
		}

	}


	// Verify we have all args set
	if((!bHCAMMode && nargs_set != 5) || (bHCAMMode && nargs_set != 6))
	{
		display_usage();
		return 0;
	}

	// Create cam class
	ICamViewSocket *pCamView = new ICamViewSocket(bHCAMMode, camID);

	//initialise 
	pCamView->Initialise(camhost,camport, camuser, campass);
	
	// If we are moving the camera, perform the operation and then exit
	if (move.length() > 0) 
	{
	  printf("Moving Camera then exiting\n");
	  pCamView->Login();
	  pCamView->Movement(move);
	  pCamView->Logout();
	  exit(0);
	}
	// Resolve the argument into an IPaddress type
	if(SDLNet_ResolveHost(&ip,NULL,proxyport)==-1)
	{
		printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
		exit(3);
	}

	// open the server socket
	server=SDLNet_TCP_Open(&ip);
	if(!server)
	{
		printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
		exit(4);
	}

	// This could easily be expanded to support multiple clients
	// but for the majority of purposes there is no need.
	while(1) // wait for one client to connect, then only service that. ie zone alarm
	{
		// try to accept a connection
		client = SDLNet_TCP_Accept(server);

		if(!client)// no connection accepted, retry
		{ 
			SDL_Delay(100); //sleep 1/10th of a second
			continue;
		}
		
		// get the clients IP and port number
		remoteip=SDLNet_TCP_GetPeerAddress(client);
		if(!remoteip)
		{
			printf("SDLNet_TCP_GetPeerAddress: %s\n",SDLNet_GetError());
			continue;
		}

		// print out the clients IP and port number
		ipaddr=SDL_SwapBE32(remoteip->host);
		printf("Accepted a connection from %d.%d.%d.%d port %hu\n",
			ipaddr >> 24,
			(ipaddr >> 16)&0xff,
			(ipaddr >> 8)&0xff,
			ipaddr & 0xff,
			remoteip->port);

		// Reset output buffer
		memset(tcp_out_buff,0,65535);
	
		std::string boundary;
		// Send header on accepted stream
		boundary += "HTTP/1.0 200 OK\r\nServer: ICamviewRelay-Relay\r\nConnection: close\r\nMax-Age: 0\r\nExpires: 0\r\nCache-Control: no-cache, private\r\nPragma: no-cache\r\nContent-Type: multipart/x-mixed-replace; boundary=--BoundaryString";

		// Cpy string into buffer
		strcpy(tcp_out_buff, boundary.c_str() );

		//tcp send
		SDLNet_TCP_Send(client, tcp_out_buff,  (int)boundary.length());

		// Boolean to control the connectivity of the socket
		bool bstreaming = true;

		while(bstreaming)
		{
			//get image data	
			bool bvalid = false;
            int nfs = -1; //filesize
			static bool no_image = true;
			int ii = 0;

			// Get valid image
			// This camera is wholely unreliable this makes sure only a valid image is passed to ZM
			while( !bvalid )
			{
				// printf("Attempt: %d\n", ii++);
				
				// Login
				pCamView->Login();

				// How big is the image, <=0 is error
				nfs = pCamView->RequestImage();

				// Logout
				// TODO this takes too much time.
				pCamView->Logout();
				
				if(nfs > 0)
				{
					no_image = false; // We now have a valid image stored for good
					bvalid = true;	  // Image is valid
				}
				if( ii > attempts_per_image && !no_image) // If after n attempts there is no image received, use old
				{
					nfs = pCamView->pimagesize;	// Filesize is old filesize
					bvalid = true;	// Now valid
				}
			} // End get valid image
		
			// Convert int to str
			char tmpstr[100];
			sprintf(tmpstr, "%d", nfs);

			// Packet for a single jpeg send
			boundary = "\r\n\r\n--BoundaryString\r\nContent-type: image/jpeg\r\nContent-Length: ";
			boundary += tmpstr;
			boundary += "\r\n\r\n";
		
			// cpy the string into the buffer
			strcpy(tcp_out_buff, boundary.c_str() );

			// cpy into packet to send
			// TODO why did I comment this out so long ago and manually copy bytes?!
			// std::memcpy(tcp_out_buff + boundary.length(), pCamView->pgoodimage, nfs);
			for(int i=0; i<nfs; i++)
            {
				tcp_out_buff[i + boundary.length()] = (char)pCamView->pgoodimage[i];
            }

			int lentosend = (int)boundary.length()+nfs;
			int nbytesent = SDLNet_TCP_Send(client, tcp_out_buff,  lentosend);
			
			// check the send happened, ie socket still alive.
			if(nbytesent == 0 ||nbytesent == -1)
			{
				bstreaming = false;
				printf("Disconnect\n");
			}
			
			SDL_Delay((Uint32)(1000.0/(double)fps));

		}// end fps loop, bstreaming


		printf("Disconnect or socket fail\n");
		
		// failed or disconnect
		SDLNet_TCP_Close(client); //close client
	}
	
	// shutdown SDL_net
	SDLNet_Quit();

	// shutdown SDL
	SDL_Quit();

	return(0);
}
Exemplo n.º 5
0
 Net::~Net() {
   SDLNet_Quit();
 }
//-------------------------------------------------------------------------------------
GalactiCombatServer::~GalactiCombatServer()
{
    SDLNet_Quit();
    SDL_Quit();
}
Exemplo n.º 7
0
int network_quit() {
        SDLNet_Quit();
        return 0;
}
Exemplo n.º 8
0
int main(int argc, char **argv)
{
	Uint16 port;
	char *host,*fname,*fbasename;
	Sint32 flen,pos,p2;
	int len,blocks,i,err=0;
	Uint32 ack;
	IPaddress ip;
	UDPsocket sock;
	UDPpacket *in, *out;
	FILE *f;
	
	/* check our commandline */
	if(argc<4)
	{
		printf("%s host port file\n",argv[0]);
		exit(0);
	}
	
	/* initialize SDL */
	if(SDL_Init(0)==-1)
	{
		printf("SDL_Init: %s\n",SDL_GetError());
		exit(1);
	}

	/* initialize SDL_net */
	if(SDLNet_Init()==-1)
	{
		printf("SDLNet_Init: %s\n",SDLNet_GetError());
		exit(2);
	}

	/* get the host from the commandline */
	host=argv[1];
	/* get the port from the commandline */
	port=(Uint16) strtol(argv[2],NULL,0);
	if(!port)
	{
		printf("a server port cannot be 0.\n");
		exit(3);
	}
	/* get filename to get from server from commandline */
	fname=argv[3];

	if(SDLNet_ResolveHost(&ip,host,port)==-1)
	{
		printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
		exit(4);
	}
	
	/* open udp client socket */
	if(!(sock=SDLNet_UDP_Open(0)))
	{
		printf("SDLNet_UDP_Open: %s\n",SDLNet_GetError());
		exit(5);
	}

	/* allocate max packet */
	if(!(out=SDLNet_AllocPacket(65535)))
	{
		printf("SDLNet_AllocPacket: %s\n",SDLNet_GetError());
		exit(6);
	}
	if(!(in=SDLNet_AllocPacket(65535)))
	{
		printf("SDLNet_AllocPacket: %s\n",SDLNet_GetError());
		exit(6);
	}
	
	/* bind server address to channel 0 */
	if(SDLNet_UDP_Bind(sock, 0, &ip)==-1)
	{
		printf("SDLNet_UDP_Bind: %s\n",SDLNet_GetError());
		exit(7);
	}

	/* open output file */
	fbasename=strrchr(fname,'/');
	if(!fbasename)
		fbasename=fname;
	else
		fbasename++;
	printf("writting file: %s\n",fbasename);
	if(!(f=fopen(fbasename,"wb")))
	{
		perror("fopen");
		exit(8);
	}

	/* request file / expect filesize */
	printf("requesting file=%s\n",fname);
	out->data[0]=1<<4;
	strcpy((char*)out->data+1,fname);
	out->len=strlen(fname)+2;
	if(udpsend(sock,0,out,in,200,1,TIMEOUT)<1)
		exit(9);
	
	flen=SDLNet_Read32(in->data+1);
	len=SDLNet_Read32(in->data+5);
	blocks=(flen+len-1)/len;
	printf("flen=%d blocksize=%d blocks=%d\n",flen,len,blocks);

	/* send ready / expect file */
	printf("starting transfer\n");
	out->data[0]=2<<4;
	out->len=1;
	if(udpsend(sock,0,out,in,10,2,TIMEOUT)<1)
		exit(10);
	
	if(flen<0)
	{
		printf("file not available...\n");
		exit(11);
	}

	pos=0; /* count per 32 blocks */
	while(pos*32<blocks && !err)
	{
		/*printf("pos=%d\n",pos); */
		ack=0;
		if((pos+1)*32>=blocks)
		{
			for(i=blocks%32;i<32;i++)
				ack|=1<<i;
		}
		printf("\r                                                                  "
				"\r%3d%% %08x: ",(pos*3200)/blocks,pos*32*len);
		while(ack!=0xffffffff && !err)
		{
			i=in->data[1];
			p2=SDLNet_Read32(in->data+2);
			/*printf("received %d,%d\n",i,p2); */
			if(!(ack&1<<i) && p2>=pos*32*len)
			{
				fseek(f,p2,SEEK_SET);
				fwrite(in->data+6,in->len-6,1,f);
				ack|=1<<i;

				printf(".");
				fflush(stdout);
			}
			if(ack!=0xffffffff)
				err=udprecv(sock,in,10,2,500);
			if(err<0)
				continue; /* error... */
			if(!err)
			{
				/*printf("sending ack 0x%0X\n",ack); */
				out->data[0]=3<<4;
				SDLNet_Write32(pos*32*len,out->data+1);
				SDLNet_Write32(ack,out->data+5);
				out->len=9;
				SDLNet_UDP_Send(sock,0,out);
			}
			err=0;
		}
		pos++;
	}
	
	printf("\ndone.\n");

	fclose(f);
	
	/* close the socket */
	SDLNet_UDP_Close(sock);
	
	/* free packets */
	SDLNet_FreePacket(out);
	SDLNet_FreePacket(in);
	
	/* shutdown SDL_net */
	SDLNet_Quit();

	/* shutdown SDL */
	SDL_Quit();

	return(0);
}
Exemplo n.º 9
0
int main(int argc, char ** argv){
	//Initialize all SDL subsystems
	if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
	{
		return 1;    
	}
	//Set up the screen
	SDL_Surface * screen = NULL;
	screen = SDL_SetVideoMode( 200, 150, 32, SDL_SWSURFACE );

	//If there was an error in setting up the screen
	if( screen == NULL )
	{
		return 1;    
	}

	//Initialize SDL_ttf
	if( TTF_Init() == -1 )
	{
		return 1;    
	}

	//Initialize SDL_net
	if(SDLNet_Init() == -1){
		return 1;
	}

	//Set the window caption
	SDL_WM_SetCaption( "Five AI", NULL );

	TTF_Font *font;

	//Open the font
	font = TTF_OpenFont( "font.ttf", 19 );

	if( font == NULL )
	{
		return 1;
	}

	//Set Font Style
	TTF_SetFontStyle(font, TTF_STYLE_BOLD | TTF_STYLE_ITALIC);

	//The color of the font
	SDL_Color textColor = { 215, 215, 215 };

	SDL_Surface * msg = NULL;

	msg = TTF_RenderText_Solid(font,"Connecting",textColor);

	SDL_BlitSurface(msg,NULL,screen,NULL);

	IPaddress ip;
	TCPsocket tcpsock;
	
	// create a listening TCP socket on port 4700 (client)
	if(SDLNet_ResolveHost(&ip,"localhost",4700)==-1) {
		return 1;
	}

	bool quit = false;
	bool connected = false;
	bool success = false;
	bool finish = false;
	SDL_Event event;
	

	while(!quit) {
		//While there's an event to handle
		while( SDL_PollEvent( &event ) )
		{
			//If the user has Xed out the window
			if( event.type == SDL_QUIT )
			{
				//Quit the program
				quit = true;
			}    
		}
		if(!connected){
			tcpsock = SDLNet_TCP_Open(&ip);
			if(tcpsock){
				msg = TTF_RenderText_Solid(font,"Connected",textColor);
				connected = true;
			}
		}else{
			//success = false;
			char data[257]={0};
			char response[3]={0};
			if(SDLNet_TCP_Recv(tcpsock,data,257) > 0){
				if(data[0] != 'e'){
					int gameData[15][15] = {{0}};
					int addX = -1,addY = -1;
					for(int i = 0 ; i < 255; i ++){
						int temp = 0;
						if(data[i+1] != 0)
							temp = (data[i + 1]==data[0] ? 1 : 2);
						gameData[i/15][i%15] = temp;
					}
					AIwork(gameData,addX,addY);
					response[0] = addX;
					response[1] = addY;
					if(SDLNet_TCP_Send(tcpsock,response,3) == 3)
						success = true;
				}else{
					finish = true;
					quit = true;
				}
			}
			if(success)
				msg = TTF_RenderText_Solid(font,"Working",textColor);
		}
		SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) );
		SDL_BlitSurface(msg,NULL,screen,NULL);
		SDL_Flip(screen);
		SDL_Delay( 10 );
	}
	
	//Quit SDL_ttf
	TTF_Quit();

	//Close Network
	if(!finish && connected){
		SDLNet_TCP_Send(tcpsock,"e",2);
		SDLNet_TCP_Close(tcpsock);
	}

	//Quit SDL_net
	SDLNet_Quit();

	//Quit SDL
	SDL_Quit();
	return 0;
}
Exemplo n.º 10
0
int main(int argc, char **argv)
{
    TCPsocket sd, csd; /* Socket descriptor, Client socket descriptor */
    IPaddress ip, *remoteIP;
    int quit, quit2;
    char buffer[512];

    if (SDLNet_Init() < 0)
    {
        fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
        exit(EXIT_FAILURE);
    }

    /* Resolving the host using NULL make network interface to listen */
    if (SDLNet_ResolveHost(&ip, NULL, DEFAULT_PORT) < 0)
    {
        fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
        exit(EXIT_FAILURE);
    }

    /* Open a connection with the IP provided (listen on the host's port) */
    if (!(sd = SDLNet_TCP_Open(&ip)))
    {
        fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
        exit(EXIT_FAILURE);
    }

    /* Wait for a connection, send data and term */
    quit = 0;
    while (!quit)
    {
        /* This check the sd if there is a pending connection.
        * If there is one, accept that, and open a new socket for communicating */
        if ((csd = SDLNet_TCP_Accept(sd)))
        {
            /* Now we can communicate with the client using csd socket
            * sd will remain opened waiting other connections */

            /* Get the remote address */
            if ((remoteIP = SDLNet_TCP_GetPeerAddress(csd)))
                /* Print the address, converting in the host format */
                printf("Host connected: %x %d\n", SDLNet_Read32(&remoteIP->host), SDLNet_Read16(&remoteIP->port));
            else
                fprintf(stderr, "SDLNet_TCP_GetPeerAddress: %s\n", SDLNet_GetError());

            quit2 = 0;
            while (!quit2)
            {
                // Added this, from here
                char buf[4];

                const int message_length = *( reinterpret_cast<int*>(buf) );

                printf("Next message length %d\n", message_length);
                // ... to here

                if (SDLNet_TCP_Recv(csd, buffer, 512) > 0)
                {
                    buffer[message_length] = '\0';     // Added this, interpret the message correctly ugly fix
                    printf("Client says: %s\n", buffer);

                    if(strcmp(buffer, "exit") == 0) /* Terminate this connection */
                    {
                        quit2 = 1;
                        printf("Terminate connection\n");
                    }
                    if(strcmp(buffer, "quit") == 0) /* Quit the program */
                    {
                        quit2 = 1;
                        quit = 1;
                        printf("Quit program\n");
                    }
                }
            }

            /* Close the client socket */
            SDLNet_TCP_Close(csd);
        }
    }

    SDLNet_TCP_Close(sd);
    SDLNet_Quit();

    return EXIT_SUCCESS;
}
Exemplo n.º 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;
}
Exemplo n.º 12
0
CServer::~CServer()
{
    SAFE_DELETE (remoteIP);
    SDLNet_TCP_Close(server);
    SDLNet_Quit();
}
Exemplo n.º 13
0
/*
* network_close() - Close and clean up the networking system
*/
int network_close() {
	SDLNet_Quit(); // Close networking
	return 0; // Return 0 on success
}
Exemplo n.º 14
0
void ClientUDP::run()
{
	//init();
	assert(init());

	//open();
	assert(open());

	//resolveHost();
	assert(resolveHost());

	//allocatePacket();
	assert(allocatePacket());

	//SDL_CreateWindow("Client Window", 0, 0, 100, 100, SDL_WINDOW_OPENGL);

	/* Main loop */
	m_quit = 0;
	while (!m_quit)
	{
		//while (SDL_PollEvent(&m_evt))
		//{
		//	m_clientPackage->e = m_evt;

		//	switch (m_clientPackage->e.type)
		//	{
		//	case SDL_KEYDOWN:
		//		printf("Key press detected\n");
		//		break;

		//	case SDL_KEYUP:
		//		printf("Key release detected\n");
		//		break;

		//	case SDL_MOUSEMOTION:
		//		printf("Mouse Moved\n");
		//		break;

		//	default:
		//		break;
		//	}
		//}

		//m_packet->len = (sizeof(Package));
		//m_packet->address.host = m_srvadd.host;	/* Set the destination host */
		//m_packet->address.port = m_srvadd.port;	/* And destination port */

		printf("Type Message: \n>");
		//scanf("%s", (char *)m_packet->data);

		std::getline(std::cin, m_input);

		m_packet->address.host = m_srvadd.host;	/* Set the destination host */
		m_packet->address.port = m_srvadd.port;	/* And destination port */

		m_packet->len = m_input.length() + 256;
		
		memcpy(m_packet->data, m_input.c_str(), m_packet->len);

		//memcpy(m_packet->data, m_clientPackage->data, sizeof(Package));

		if (!(SDLNet_UDP_Send(m_socketDescriptor, -1, m_packet) > 0))
		{
			printf("SDLNet_UDP_Send failed...\n");
		}
	}

	freePacket(*m_packet);
	SDLNet_Quit();
}
Exemplo n.º 15
0
/*!
 * Release the network for netplay. It doesn't change the state of SDL
 */
void
shutdown_network ()
{
  SDLNet_Quit ();
}
Exemplo n.º 16
0
int main(int argc, char **argv)
{
	IPaddress ip,*remoteip;
	TCPsocket server,client;
	char message[1024];
	int len;
	Uint32 ipaddr;
	Uint16 port;

	/* check our commandline */
	if(argc<2)
	{
		printf("%s port\n",argv[0]);
		exit(0);
	}

	/* initialize SDL */
	if(SDL_Init(0)==-1)
	{
		printf("SDL_Init: %s\n",SDL_GetError());
		exit(1);
	}

	/* initialize SDL_net */
	if(SDLNet_Init()==-1)
	{
		printf("SDLNet_Init: %s\n",SDLNet_GetError());
		exit(2);
	}

	/* get the port from the commandline */
	port=(Uint16)strtol(argv[1],NULL,0);

	/* Resolve the argument into an IPaddress type */
	if(SDLNet_ResolveHost(&ip,NULL,port)==-1)
	{
		printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
		exit(3);
	}

	/* open the server socket */
	server=SDLNet_TCP_Open(&ip);
	if(!server)
	{
		printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
		exit(4);
	}

	while(1)
	{
		/* try to accept a connection */
		client=SDLNet_TCP_Accept(server);
		if(!client)
		{ /* no connection accepted */
			/*printf("SDLNet_TCP_Accept: %s\n",SDLNet_GetError()); */
			SDL_Delay(100); /*sleep 1/10th of a second */
			continue;
		}

		/* get the clients IP and port number */
		remoteip=SDLNet_TCP_GetPeerAddress(client);
		if(!remoteip)
		{
			printf("SDLNet_TCP_GetPeerAddress: %s\n",SDLNet_GetError());
			continue;
		}

		/* print out the clients IP and port number */
		ipaddr=SDL_SwapBE32(remoteip->host);
		printf("Accepted a connection from %d.%d.%d.%d port %hu\n",
			ipaddr>>24,
			(ipaddr>>16)&0xff,
			(ipaddr>>8)&0xff,
			ipaddr&0xff,
			remoteip->port);

		/* read the buffer from client */
		len=SDLNet_TCP_Recv(client,message,1024);
		SDLNet_TCP_Close(client);
		if(!len)
		{
			printf("SDLNet_TCP_Recv: %s\n",SDLNet_GetError());
			continue;
		}

		/* print out the message */
		printf("Received: %.*s\n",len,message);

		if(message[0]=='Q')
		{
			printf("Quitting on a Q received\n");
			break;
		}
	}

	/* shutdown SDL_net */
	SDLNet_Quit();

	/* shutdown SDL */
	SDL_Quit();

	return(0);
}
Exemplo n.º 17
0
Arquivo: dnr.c Projeto: manish05/TCR
int main(int argc, char **argv)
{
	IPaddress ip;
	const char *host;
	Uint8 *ipaddr;
	
	/* check our commandline */
	if(argc>1 && !strncmp("-h",argv[1],2))
	{
		printf("%s host|ip\n",argv[0]);
		exit(0);
	}
	
	/* do a little version check for information */
	{
		SDL_version compile_version;
		const SDL_version *link_version=SDLNet_Linked_Version();
		SDL_NET_VERSION(&compile_version);
		printf("compiled with SDL_net version: %d.%d.%d\n", 
				compile_version.major,
				compile_version.minor,
				compile_version.patch);
		printf("running with SDL_net version: %d.%d.%d\n", 
				link_version->major,
				link_version->minor,
				link_version->patch);
	}

	/* initialize SDL */
	if(SDL_Init(0)==-1)
	{
		printf("SDL_Init: %s\n",SDL_GetError());
		exit(1);
	}

	/* initialize SDL_net */
	if(SDLNet_Init()==-1)
	{
		printf("SDLNet_Init: %s\n",SDLNet_GetError());
		exit(2);
	}

#ifndef WIN32 /* has no gethostname that we can use here... */
	{
		char localhostname[256];
		if((gethostname(localhostname, 256)>=0))
		{
			printf("Local Host: %s\n",localhostname);
			printf("Resolving %s\n",localhostname);
			if(SDLNet_ResolveHost(&ip,localhostname,0)==-1)
			{
				printf("Could not resolve host \"%s\"\n%s\n",
						localhostname,SDLNet_GetError());
			}
			else
			{
				/* use the IP as a Uint8[4] */
				ipaddr=(Uint8*)&ip.host;

				/* output the IP address nicely */
				printf("Local IP Address : %d.%d.%d.%d\n",
						ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);
			}
		}
	}
#endif
	
	if(argc<2)
		exit(0);
	
	/* Resolve the argument into an IPaddress type */
	printf("Resolving %s\n",argv[1]);
	if(SDLNet_ResolveHost(&ip,argv[1],0)==-1)
	{
		printf("Could not resolve host \"%s\"\n%s\n",argv[1],SDLNet_GetError());
		exit(3);
	}

	/* use the IP as a Uint8[4] */
	ipaddr=(Uint8*)&ip.host;

	/* output the IP address nicely */
	printf("IP Address : %d.%d.%d.%d\n",
			ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);

	/* resolve the hostname for the IPaddress */
	host=SDLNet_ResolveIP(&ip);

	/* print out the hostname we got */
	if(host)
		printf("Hostname   : %s\n",host);
	else
		printf("No Hostname found\n");

	/* shutdown SDL_net */
	SDLNet_Quit();

	/* shutdown SDL */
	SDL_Quit();

	return(0);
}
CNetManager::~CNetManager()
{
	SDLNet_Quit();
}
Exemplo n.º 19
0
void TcpNet::quit()
{
    SDLNet_Quit();
}
Exemplo n.º 20
0
void net_cleanup()
{
    SDLNet_FreePacket(gPacket);
    SDLNet_Quit();
}
Exemplo n.º 21
0
void MySocketConnection::quitNetwork() {
	SDLNet_Quit();
}
Exemplo n.º 22
0
void init_stuff()
{
	int seed;

	Uint32 (*my_timer_pointer) (unsigned int) = my_timer;

	//TODO: process command line options
	chdir(datadir);

	//Initialize all strings
	init_translatables();

#ifdef WRITE_XML
	load_translatables();//Write to the current working directory - hopefully we'll have write rights here...
#endif

	//read the config file
	read_config();

	//Parse command line options
	read_command_line();

	//OK, we have the video mode settings...
	setup_video_mode(full_screen,video_mode);
	//now you may set the video mode using the %<foo> in-game
	video_mode_set=1;

	//Good, we should be in the right working directory - load all translatables from their files
	load_translatables();

	init_video();
	resize_window();
	init_gl_extensions();
#ifdef CAL3D
	create_cal3d_model();
	init_cal3d_model();
#endif
	seed = time (NULL);
	srand (seed);

	cache_system_init(MAX_CACHE_SYSTEM);
	init_texture_cache();
	init_md2_cache();
	init_e3d_cache();
	init_2d_obj_cache();
	load_ignores();
	load_filters();
	load_e3d_list();
	load_e2d_list();
	load_part_list();
	load_knowledge_list();
	load_cursors();
	build_cursors();
	change_cursor(CURSOR_ARROW);
	build_glow_color_table();


	init_actors_lists();
	memset(tile_list, 0, sizeof(tile_list));
	memset(lights_list, 0, sizeof(lights_list));
	init_particles_list();
	memset(actors_defs, 0, sizeof(actors_defs));
	init_actor_defs();

	load_map_tiles();

	//lights setup
	build_global_light_table();
	build_sun_pos_table();
	reset_material();
	init_lights();
	disable_local_lights();
	init_colors();
	clear_error_log();
	clear_conn_log();
	clear_thunders();
	build_rain_table();
	read_bin_cfg();
	build_levels_table();//for some HUD stuff
	init_scale_array();

	if(!no_sound)init_sound();

	//initialize the fonts
	init_fonts();
	check_gl_errors();

	//load the necesary textures
	//font_text=load_texture_cache("./textures/font.bmp",0);
	icons_text=load_texture_cache("./textures/gamebuttons.bmp",0);
	hud_text=load_texture_cache("./textures/gamebuttons2.bmp",0);
	cons_text=load_texture_cache("./textures/console.bmp",255);
	sky_text_1=load_texture_cache("./textures/sky.bmp",70);
	particle_textures[0]=load_texture_cache("./textures/particle0.bmp",0);
	particle_textures[1]=load_texture_cache("./textures/particle1.bmp",0);
	particle_textures[2]=load_texture_cache("./textures/particle2.bmp",0);
	particle_textures[3]=load_texture_cache("./textures/particle3.bmp",0);
	particle_textures[4]=load_texture_cache("./textures/particle4.bmp",0);
	particle_textures[5]=load_texture_cache("./textures/particle5.bmp",0);
	particle_textures[6]=load_texture_cache("./textures/particle6.bmp",0);
	particle_textures[7]=load_texture_cache("./textures/particle7.bmp",0);

	items_text_1=load_texture_cache("./textures/items1.bmp",0);
	items_text_2=load_texture_cache("./textures/items2.bmp",0);
	items_text_3=load_texture_cache("./textures/items3.bmp",0);
	items_text_4=load_texture_cache("./textures/items4.bmp",0);
	items_text_5=load_texture_cache("./textures/items5.bmp",0);
	items_text_6=load_texture_cache("./textures/items6.bmp",0);
	items_text_7=load_texture_cache("./textures/items7.bmp",0);
	items_text_8=load_texture_cache("./textures/items8.bmp",0);
	items_text_9=load_texture_cache("./textures/items9.bmp",0);

	portraits1_tex=load_texture_cache("./textures/portraits1.bmp",0);
	portraits2_tex=load_texture_cache("./textures/portraits2.bmp",0);
	portraits3_tex=load_texture_cache("./textures/portraits3.bmp",0);
	portraits4_tex=load_texture_cache("./textures/portraits4.bmp",0);
	portraits5_tex=load_texture_cache("./textures/portraits5.bmp",0);
	halo_tex=load_texture_cache("./textures/halo.bmp",0);

	if(have_multitexture)ground_detail_text=load_texture_cache("./textures/ground_detail.bmp",255);
	check_gl_errors();
	create_char_error_str[0]=0;
	init_opening_interface();
	init_hud_interface();

	if(SDLNet_Init()<0)
 		{
			char str[120];
			sprintf(str,"%s: %s\n",failed_sdl_net_init,SDLNet_GetError());
			log_error(str);
			SDLNet_Quit();
			SDL_Quit();
			exit(2);
		}

	if(SDL_InitSubSystem(SDL_INIT_TIMER)<0)
		{
 			char str[120];
			sprintf(str, "%s: %s\n", failed_sdl_timer_init,SDL_GetError());
			log_error(str);
			SDL_Quit();
		 	exit(1);
		}
	SDL_SetTimer (1000/(18*4), my_timer_pointer);

	ReadXML("languages/en/Encyclopedia/index.xml");
	read_key_config();
	load_questlog();
	init_buddy();

	//initiate function pointers
	init_attribf();

	//we might want to do this later.
	connect_to_server();
}
Exemplo n.º 23
0
NetBaseUDP::~NetBaseUDP()
{
	SDLNet_FreePacket(mPacket);

	SDLNet_Quit();
}
Exemplo n.º 24
0
void Server::Quit()
{
	SDLNet_FreePacket(p);
	SDLNet_Quit();
}
Server::~Server() {
    logOut();
    SDLNet_Quit();
}
Exemplo n.º 26
0
/* I_ShutdownNetwork
 *
 * Shutdown the network code
 */
void I_ShutdownNetwork(void)
{
        SDLNet_FreePacket(udp_packet);
        SDLNet_Quit();
}
Exemplo n.º 27
0
int main(int argc, char **argv)
{
	IPaddress ip,*remoteip;
	TCPsocket server=NULL,client=NULL;
	Uint32 ipaddr,now,last;
	float lag;
	Uint16 port;
	SyncPacket sp;
	int done;
	int minoff=5; /*that's + or - */
	
	/* check our commandline */
	if(argc<2)
	{
		printf("%s port [minoff]\n",argv[0]);
		exit(0);
	}
	
	/* initialize SDL */
	if(SDL_Init(0)==-1)
	{
		printf("SDL_Init: %s\n",SDL_GetError());
		exit(1);
	}

	/* initialize SDL_net */
	if(SDLNet_Init()==-1)
	{
		printf("SDLNet_Init: %s\n",SDLNet_GetError());
		exit(2);
	}

	/* get the port from the commandline */
	port=(Uint16) strtol(argv[1],NULL,0);

	/* get the minoff from the commandline */
	if(argc>2)
		minoff=strtol(argv[2],NULL,0);

	/* Resolve the argument into an IPaddress type */
	if(SDLNet_ResolveHost(&ip,NULL,port)==-1)
	{
		printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
		exit(3);
	}

	/* open the server socket */
	server=SDLNet_TCP_Open(&ip);
	if(!server)
	{
		printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
		exit(4);
	}

	while(1)
	{
		client=NULL;
		while(!client)
		{ /* no connection accepted */
			client=SDLNet_TCP_Accept(server);
			if(!client)
				SDL_Delay(100); /*sleep 1/10th of a second */
		}
		
		/* get the clients IP and port number */
		remoteip=SDLNet_TCP_GetPeerAddress(client);
		if(!remoteip)
		{
			printf("SDLNet_TCP_GetPeerAddress: %s\n",SDLNet_GetError());
			SDLNet_TCP_Close(client);
			continue;
		}

		/* print out the clients IP and port number */
		ipaddr=SDL_SwapBE32(remoteip->host);
		printf("Accepted a connection from %d.%d.%d.%d port %hu\n",
				ipaddr>>24,
				(ipaddr>>16)&0xff,
				(ipaddr>>8)&0xff,
				ipaddr&0xff,
				remoteip->port);

		done=0;
		lag=0;
		sp.type=0;
		sp.data.u.s=SDL_GetTicks();
		sendSyncPacket(client,&sp);
		now=SDL_GetTicks();
		while(!done)
		{
			last=now;
			recvSyncPacket(client,&sp);
			now=SDL_GetTicks();
			lag=(now-last)/2.0f;
			
			printSyncPacket(&sp);
			switch(sp.type)
			{
				case 0:
					sp.type=1;
					sp.data.u.s=SDL_GetTicks()+(Uint32) lag;
					sendSyncPacket(client,&sp);
					break;
				case 1:
					sp.type=2;
				case 2:
					sp.data.s.c=now-(Uint32) lag-sp.data.u.c;
					if(sp.data.s.c<minoff && sp.data.s.c>-minoff)
						/* too strict!
							&& sp.data.s.s<minoff && sp.data.s.s>-minoff)
						*/
					{
						sp.type=3;
						sp.data.u.s=SDL_GetTicks()+(Uint32) lag+minoff*100;
					}
					else
						sp.data.u.s=SDL_GetTicks()+(Uint32) lag;
					sendSyncPacket(client,&sp);
					if(sp.type==3)
					{
						printf("wait until %u\n",sp.data.u.s);
#ifdef DO_BUSY
						while(SDL_GetTicks()<sp.data.u.s);
#else
						SDL_Delay(sp.data.u.s-SDL_GetTicks());
#endif
						printf("TIME = %u\n",SDL_GetTicks());
						done=1;
					}
					break;
				default:
					done=1;
					break;
			}
			printf("now=%u (lag=%.2f)\n",now,lag);
			sp.type=10;
		}

		SDLNet_TCP_Close(client);
	}

	SDLNet_TCP_Close(server);
	
	/* shutdown SDL_net */
	SDLNet_Quit();

	/* shutdown SDL */
	SDL_Quit();

	return(0);
}
 UdpConnection::~UdpConnection() {
     freeResources();
     SDLNet_Quit();
 }
Exemplo n.º 29
0
/**
 * @brief client program entry point
 * @param argc number of arguments
 * @param argv pointer to array of strings
 * @return return value of program
 */
int main(int argc, char **argv)
{
    ClientSocket client;
	IPaddress srvadd;
	bool quit;
    bool obtainingInput = false;

    if (!ConsoleInit(CLEAR_LINE_ON_ENTER)) {
        printf("ERROR: ConsoleInit failed\n");
        exit(EXIT_FAILURE);
    }

	// Check for parameters
	if (argc < 3) {
		ConsolePrintf("ERROR: Usage: %s host port\n",
                      argv[0]);
		exit(EXIT_FAILURE);
	}

	// Initialize SDL_net
	if (SDLNet_Init() != 0) {
		ConsolePrintf("ERROR: SDLNet_Init: %s\n",
                      SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
    ConsolePrintf("SDLNet Ready\n");

	// Resolve server name
	if (!client.toIPaddress(&srvadd, argv[1], atoi(argv[2])))
	{
		ConsolePrintf("ERROR: SDLNet_ResolveHost(%s:%d): %s\n",
                      argv[1],
                      atoi(argv[2]),
                      SDLNet_GetError());
		exit(EXIT_FAILURE);
	}

    // Host and Port are in network order
    ConsolePrintf("Server: %d.%d.%d.%d:%d\n",
                  (srvadd.host >>  0) & 0xFF,
                  (srvadd.host >>  8) & 0xFF,
                  (srvadd.host >> 16) & 0xFF,
                  (srvadd.host >> 24) & 0xFF,
                  SDLNet_Read16(&srvadd.port));

    // Initialize client
    if (!client.init(USE_RANDOM_PORT, UDP_MAX_PACKET_SIZE, &srvadd)) {
        ConsolePrintf("ERROR: client.init(): failed\n");
        exit(EXIT_FAILURE);
    }
    ConsolePrintf("Client Ready\n");

    // Initialize the Messenger protocol
    if (!InitMessengerProtocol()) {
        ConsolePrintf("ERROR: InitMessengerProtocol() failed\n");
        exit(EXIT_FAILURE);
    }
    ConsolePrintf("Messenger Protocol Ready\n");

	// Main loop
	quit = false;
	while (!quit) {
        // get input
        if (ConsoleHandleInput()) {
            // user is typing something
            obtainingInput = true;
        } else {
            if (obtainingInput) {
                // user finished typing something
                if (!HandleUserInput(&client)) {
                    // time to quit
                    quit = true;
                }
            }

            obtainingInput = false;
        }

        // get network input
        if (!quit) {
            ClientPacket *pkt;

            pkt = client.allocPacket();
            if (pkt) {
                if (client.receiveData(pkt)) {
                    // handle data
                    if (!HandleServerData(&client, pkt)) {
                        quit = true;
                    }
                }

                // finish with the packet, free it
                client.freePacket(pkt);
            }
        } // end network
	}

    ConsolePrintf("Quiting...\n");

    // cleanup
    ShutdownMessengerProtocol();
    client.shutdown();
	SDLNet_Quit();

	return EXIT_SUCCESS;
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
	UNUSED(argc);
	UNUSED(argv);

	if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) != 0)
	{
		fprintf(stderr, "Could not initialise SDL: %s\n", SDL_GetError());
		return -1;
	}
	if (SDLNet_Init() == -1)
	{
		fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
	if (!SDL_SetVideoMode(320, 200, 0, 0))
	{
		fprintf(stderr, "Could not set video mode: %s\n", SDL_GetError());
		SDL_Quit();
		exit(-1);
	}

	ConfigLoadDefault(&gConfig);
	ConfigLoad(&gConfig, GetConfigFilePath(CONFIG_FILE));
	EventInit(&gEventHandlers, NULL, false);

	NetInputClient client;
	NetInputClientInit(&client);
	NetInputClientConnect(&client, 0x7F000001);	// localhost

	printf("Press esc to exit\n");

	Uint32 ticksNow = SDL_GetTicks();
	Uint32 ticksElapsed = 0;
	for (;;)
	{
		Uint32 ticksThen = ticksNow;
		ticksNow = SDL_GetTicks();
		ticksElapsed += ticksNow - ticksThen;
		if (ticksElapsed < 1000 / FPS_FRAMELIMIT)
		{
			SDL_Delay(1);
			debug(D_VERBOSE, "Delaying 1 ticksNow %u elapsed %u\n", ticksNow, ticksElapsed);
			continue;
		}
		EventPoll(&gEventHandlers, SDL_GetTicks());
		int cmd = GetOnePlayerCmd(
			&gEventHandlers,
			&gConfig.Input.PlayerKeys[0],
			false,
			INPUT_DEVICE_KEYBOARD,
			0);
		if (cmd)
		{
			printf("Sending %s + %s\n",
				CmdStr(cmd & (CMD_LEFT | CMD_RIGHT | CMD_UP | CMD_DOWN)),
				CmdStr(cmd & (CMD_BUTTON1 | CMD_BUTTON2 | CMD_BUTTON3 | CMD_BUTTON4 | CMD_ESC)));
			NetInputClientSend(&client, cmd);
		}

		// Check keyboard escape
		if (KeyIsPressed(&gEventHandlers.keyboard, SDLK_ESCAPE))
		{
			break;
		}

		ticksElapsed -= 1000 / FPS_FRAMELIMIT;
	}

	NetInputClientTerminate(&client);
	EventTerminate(&gEventHandlers);
	SDLNet_Quit();
	SDL_Quit();
	return 0;
}