示例#1
0
Vec2 MovePacket::GetVelocity() const
{
	return Vec2(
		Uint32toFloat( SDLNet_Read32( &data_[14] ) ),
		Uint32toFloat( SDLNet_Read32( &data_[18] ) )
		);
}
示例#2
0
void
mousefocus(WlistPtr list, int line, Wpoint mousexy)
{
  float color[4] = { 0.05f, 0.05f, 0.05f, .8f };
  int   x, y;
  int   width    = 400;
  int   h        = list->height/list->nblines;
  int   l        = (list->y+list->height-mousexy.v)/h;
  int   s        = 14;
  int   height   = s*6;
  char  str[255];

  //draw a beautifull transparent box using alpha trucs
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glColor4fv(color);

  //find pos x, y
  x = list->x + list->width/2 - width/2;
  y = list->y+list->height-((l+1)*h)+0.5*h+(0.25*height)-1;//+((list->y+list->height-mousexy.v)/h)*h;

  glBegin(GL_QUADS); 
  glVertex3f(x, y, 0.0f);   //top left
  glVertex3f(x+width, y, 0.0f);   //top right
  glVertex3f(x+width, y-height, 0.0f);  //Bottom right
  glVertex3f(x, y-height, 0.0f);  //Bottom left  
  glEnd();
  glDisable(GL_BLEND);

  glColor3f(0.9,.3, .3);
  //draw text now
  y -=2*s;
  x+=10;
  sprintf(str, "Server       : %d.%d.%d.%d",
	  (SDLNet_Read32(&servers[line].ipaddress.host) & 0xff000000) >> 24,
	  (SDLNet_Read32(&servers[line].ipaddress.host) & 0x00ff0000) >> 16,
	  (SDLNet_Read32(&servers[line].ipaddress.host) & 0x0000ff00) >> 8,
	  SDLNet_Read32(&servers[line].ipaddress.host) & 0x000000ff);
  //x=list->x+list->width/2-strlen(str)*s*1.5/2;
  drawText(gameFtx, x, y, s, str);
  y -=s;

  glColor3f(.1,.9, .1);
  sprintf(str, "Version      : %s",servers[line].version);
  //x=list->x+list->width/2-strlen(str)*( game->screen->vp_w / (50 * 1.5) )*1.5/2;
  drawText(gameFtx, x, y, s, str);
  y -=s;

  glColor3f(.4,.4, .9);
  sprintf(str, "Speed        : %s",speed_list[servers[line].speed]);
  //x=list->x+list->width/2-strlen(str)*( game->screen->vp_w / (50 * 1.5) )*1.5/2;
 //y = game->screen->vp_h - 90;
  drawText(gameFtx, x, y, s, str);

  y -=s;
  sprintf(str, "Size         : %s", arena_list[servers[line].size]);
  //x=list->x+list->width/2-strlen(str)*( game->screen->vp_w / (50 * 1.5) )*1.5/2;
  //y = game->screen->vp_h - 110;
  drawText(gameFtx, x, y, s, str);
}
示例#3
0
Vec2 MovePacket::GetPosition() const
{
	return Vec2(
		Uint32toFloat( SDLNet_Read32( &data_[6] ) ),
		Uint32toFloat( SDLNet_Read32( &data_[10] ) )
		);
}
示例#4
0
void
action(WlistPtr list)
{
  char server[255], port[255];
  IPaddress *ipaddress=NULL;

     if(  (servers[getcurrent_wlist(list)].packets > 0 && ((servers[getcurrent_wlist(list)].ping/servers[getcurrent_wlist(list)].packets) > PINGLIMIT)) || strcmp(servers[getcurrent_wlist(list)].version, VERSION))
	return;

      //str = getcell_wlist ( list, getcurrent_wlist(list), 0);
      ipaddress = (IPaddress *)getCell_wlist( list, getcurrent_wlist(list), 0);

      if( ipaddress == NULL )
	{
	  fprintf(stderr, "error ipaddress null\n");
	  return;
	}

      //getting server address
      sprintf(server, "%d.%d.%d.%d", 
	      (SDLNet_Read32(&ipaddress->host) & 0xff000000) >> 24,
	      (SDLNet_Read32(&ipaddress->host) & 0x00ff0000) >> 16,
	      (SDLNet_Read32(&ipaddress->host) & 0x0000ff00) >> 8,
	      SDLNet_Read32(&ipaddress->host) & 0x000000ff);

      //getting port
      sprintf(port, "%d", ipaddress->port);

      if( server == NULL )
	return;
      printf("server %s\n", server);
      //strcpy(server,"");
      // sscanf(str, "%[.0-9]:%[.0-9]", server, port);
/*       strcpy(game->settings->server, server); */
/*       strcpy(game->settings->port, port); */
      //if( !strcmp(server, "") )
      //if(server == NULL )
      //	return;
      setconnection(server, port);
      isConnected=0;
      isLogged=0;
      printf("server %s port %s\n", server, port);
      tracker_close();
      freeRootControl(tracker.trackerControls);
      tracker.trackerControls=NULL;
      tracker.serverlist=NULL;
      tracker.servertext=NULL;
      //      tracker.listscroll=NULL;
      changeCallback(&netConnectCallbacks, &trackerCallbacks);
}
void TCP_NetServer::recvThreadFunc(RecvThreadArg * arg)
{
	TCP_NetServer * svr = arg->svr;
	int remoteIndex = arg->remoteIndex;
	delete arg; //so we don't forget later

	for (;;) {
		ulong player;
		TCPsocket sock = svr->getRemoteSocketByIndex(remoteIndex, player);

		char header[TCP_HEADER_SIZE];
		if (!receiveOnSocket(sock, header, sizeof(header))) {
			NETMSG("TCP send error, will drop remote client");
			svr->removeRemoteSocket(sock);
			break;
		}

		ulong playerId = SDLNet_Read32(header);
		ulong msgDataLen = SDLNet_Read32(header);
		if (true /*playerId == sp->localPlayerId*/) { //TODO NET handle this
			//message is for us
		}
		else {
			TCPsocket sendSock = svr->getRemoteSocketByPlayer(playerId);

			//pass it on
			const size_t bufferLen = sizeof(header) + msgDataLen;
			char * const buffer = reinterpret_cast<char *> (malloc(bufferLen));
			if (buffer == NULL) {
				ERRORLOG("Memory alloc error");
				break;
			}

			memcpy(buffer, header, sizeof(header));
			if (!receiveOnSocket(sock, buffer + sizeof(header), msgDataLen)) {
				free(buffer);
				svr->removeRemoteSocket(sock);
				break;
			}

			if (SDLNet_TCP_Send(sendSock, buffer, bufferLen) < bufferLen) {
				svr->removeRemoteSocket(sendSock);
				NETMSG("TCP send error, will drop remote client with ID %d", playerId);
				break;
			}
		}
	}
}
示例#6
0
bool PacketManager::Read32(Uint32 *val){
  if(dataLength < dataPos + sizeof(Uint32))return false;
  Uint32 v = SDLNet_Read32(buffer + dataPos);
  dataPos += sizeof(Uint32);
  if(val != NULL)*val = v;
  return true;
}
示例#7
0
uint32_t Read32(FILE *in)
{
  uint32_t render;
  int i_dont_care = fread(&render, 1, 4, in);
  i_dont_care = 0;
  return SDLNet_Read32(&render);
}
示例#8
0
文件: net.c 项目: esohns/jnb
void
packetToBuf(const struct NetPacket* pkt, char* buf)
{
	*((Uint32*)(buf +  0)) = SDLNet_Read32(&pkt->cmd);
	*((Uint32*)(buf +  4)) = SDLNet_Read32(&pkt->arg);
	*((Uint32*)(buf +  8)) = SDLNet_Read32(&pkt->arg2);
	*((Uint32*)(buf + 12)) = SDLNet_Read32(&pkt->arg3);
	*((Uint32*)(buf + 16)) = SDLNet_Read32(&pkt->arg4);
/*
	*((unsigned long *) (buf +  0)) = htonl(pkt->cmd);
	*((unsigned long *) (buf +  4)) = htonl((unsigned long) pkt->arg);
	*((unsigned long *) (buf +  8)) = htonl((unsigned long) pkt->arg2);
	*((unsigned long *) (buf + 12)) = htonl((unsigned long) pkt->arg3);
	*((unsigned long *) (buf + 16)) = htonl((unsigned long) pkt->arg4);
*/
}
示例#9
0
bool PacketManager::ReadF(float *val){
  if(dataLength < dataPos + sizeof(float))return false;
  Uint32 tmp = SDLNet_Read32(buffer + dataPos);
  float *v = (float*)(&tmp);
  dataPos += sizeof(float);
  if(val != NULL)*val = *v;
  return true;
}
示例#10
0
Connection* Connection_create(const char* ip, Uint16 port)
{
    Connection* self = (Connection*)calloc(1, sizeof(Connection));
    if(!self)
    {
        return NULL;
    }

    if(SDLNet_ResolveHost(&self->address, ip, port))
    {
        Connection_destroy(&self);
        return NULL;
    }

    if(!(self->socket = SDLNet_TCP_Open(&self->address)))
    {
        Connection_destroy(&self);
        return NULL;
    }

    if(!(self->socket_set = SDLNet_AllocSocketSet(1)))
    {
        Connection_destroy(&self);
        return NULL;
    }

    if(SDLNet_TCP_AddSocket(self->socket_set, self->socket) == -1)
    {
        Connection_destroy(&self);
        return NULL;
    }

    if(SDLNet_CheckSockets(self->socket_set, 5000) == 1)
    {
        Uint8 message = Connection_recv_flag(self);
        if(message == CONNECTED)
        {
            Uint8 buffer[6] = {0};
            Connection_recv_data(self, buffer, 6);

            self->local_address.host = SDLNet_Read32(buffer);
            self->local_address.port = SDLNet_Read16(buffer + 4);
            printf("Successfully connected to server\n");
            return self;
        }
        else if(message == FULL)
        {
            printf("Server is full\n");
        }
    }
    else
    {
        printf("Server is not responding\n");
    }

    Connection_destroy(&self);
    return NULL;
}
void NetworkCommandBuffer::AddCharToCommandSize ( char chr )
{
	size_buffer[size_buffer_used] = chr;
	++size_buffer_used;
	if (size_buffer_used == 4)
	{
		current_command_size = SDLNet_Read32(size_buffer);
		size_buffer_used = 0;
	}
}
示例#12
0
Client* Client_create(TCPsocket socket)
{
    Client* self = malloc(sizeof(Client));
    self->socket = socket;

    IPaddress* client_ip = SDLNet_TCP_GetPeerAddress(socket);
    self->ip = SDLNet_Read32(&client_ip->host);
    self->port = SDLNet_Read16(&client_ip->port);

    return self;
}
示例#13
0
Uint32
getint(TCPsocket sock)
{
   Uint32 cmd;
   int recvdata = recvall(sock, (unsigned char *) &cmd, sizeof(cmd));

   if (recvdata != sizeof(cmd))
   {
      return 0;
   }
   return SDLNet_Read32(&cmd);
}
示例#14
0
char *
addressToStr( WlistPtr list, int line, int col )
{
  char *str = malloc(255);
  IPaddress *ipaddress;

  ipaddress = ( IPaddress *)list->lines[line][col];
  if( ipaddress == NULL )
    {
      strcpy(str, "N/A");
    } else {

      sprintf(str, "%d.%d.%d.%d",
	      (SDLNet_Read32(&ipaddress->host) & 0xff000000) >> 24,
	      (SDLNet_Read32(&ipaddress->host) & 0x00ff0000) >> 16,
	      (SDLNet_Read32(&ipaddress->host) & 0x0000ff00) >> 8,
	      SDLNet_Read32(&ipaddress->host) & 0x000000ff
	      );
    }
  return str;
}
示例#15
0
connection receive_data(config& cfg, connection connection_num, bandwidth_in_ptr* bandwidth_in)
{
	if(!socket_set) {
		return 0;
	}

	check_error();

	if(disconnection_queue.empty() == false) {
		const network::connection sock = disconnection_queue.front();
		disconnection_queue.pop_front();
		throw error("",sock);
	}

	if(bad_sockets.count(connection_num) || bad_sockets.count(0)) {
		return 0;
	}

	if(sockets.empty()) {
		return 0;
	}

	const int res = SDLNet_CheckSockets(socket_set,0);

	for(std::set<network::connection>::iterator i = waiting_sockets.begin(); res != 0 && i != waiting_sockets.end(); ) {
		connection_details& details = get_connection_details(*i);
		const TCPsocket sock = details.sock;
		if(SDLNet_SocketReady(sock)) {

			// See if this socket is still waiting for it to be assigned its remote handle.
			// If it is, then the first 4 bytes must be the remote handle.
			if(is_pending_remote_handle(*i)) {
				union {
				char data[4] ALIGN_4;
				} buf;
				int len = SDLNet_TCP_Recv(sock,&buf,4);
				if(len != 4) {
					throw error("Remote host disconnected",*i);
				}

				const int remote_handle = SDLNet_Read32(&buf);
				set_remote_handle(*i,remote_handle);

				continue;
			}

			waiting_sockets.erase(i++);
			SDLNet_TCP_DelSocket(socket_set,sock);
			network_worker_pool::receive_data(sock);
		} else {
			++i;
		}
	}
示例#16
0
std::string Peer::getIP(const Uint32 host) const
{
	Uint32 ip = SDLNet_Read32(&host);

	//split 32 bit into 8 bits
	int a = (ip >> 24) & 0xFF;
	int b = (ip >> 16) & 0xFF;
 	int c = (ip >> 8) & 0xFF;
 	int d = ip & 0xFF;

 	// return address in format(a.b.c.d)
	return a + "." + b + "." + "." + c + "." + d;
}
示例#17
0
static bool TryParseCmd(UDPpacket *packet, void *data)
{
	size_t readlen = sizeof(NetMsgCmd);
	NetInput *n = data;
	while (packet->len >= (int)readlen)
	{
		NetMsgCmd *msg = (NetMsgCmd *)packet->data;
		Uint32 cmd = SDLNet_Read32(&msg->cmd);
		n->Cmd |= cmd;
		packet->len -= readlen;
		packet->data += readlen;
	}
	return true;
}
示例#18
0
文件: CNet.cpp 项目: wikiti/ullPong
/**
 * @brief Inicia un socket
 *
 * @param the_sdl_socket Socket del cliente a crear.
 *
 * Se intentará crear el socket. Si nada falla, se creará el socket. Si ha fallado algo, SDL_net generará un error.
 */
void CClientSocket::SetSocket (TCPsocket the_sdl_socket) {
    CTcpSocket::SetSocket (the_sdl_socket);
    IPaddress* ips;
    if ((ips = SDLNet_TCP_GetPeerAddress(m_Socket))) {
    /* Print the address, converting it onto the host format */
        m_RemoteIp.SetIp(*ips);
        Uint32 hbo = m_RemoteIp.GetHost();
        Uint16 pbo = m_RemoteIp.GetPort();
        std::cout << "Client connected: " << SDLNet_Read32(&hbo) << ' '
            << SDLNet_Read16 (&pbo) << std::endl;
    }
    else
        std::cerr << "SDLNet_TCP_GetPeerAddress: " << SDLNet_GetError() << std::endl;
}
示例#19
0
/*///////////////////////////////////////////////////////////

	Function for operation on threads 
/////////////////////////////////////////////////////////////*/
void * handle(void * data)
{
	struct threadID * temp_thread=(struct threadID *) data;
	int quit1=1;
	int *temp=(int *) data;
	char buffer[512];
	TCPsocket client_socket;
	while(1)   // to make sure thread doesn't terminate
	{
		if(temp_thread->status==0)
		{
			sem_wait(&(temp_thread->binary_sem));
		}
		printf("\n Activating thread");
		// here thread start receiving data from client	
		while(quit1)
		{
			if(client_socket=SDLNet_TCP_Accept(temp_thread->client.server_socket))
			{	
				printf("\nGetting request from client");
				quit1=1;
				while(quit1)
				{
					if(temp_thread->client.client_ipaddress=SDLNet_TCP_GetPeerAddress(client_socket))
						printf("\n Listening from client:%x",SDLNet_Read32(&temp_thread->client.client_ipaddress->host));
					if(SDLNet_TCP_Recv(client_socket,buffer,512))
					{
						printf("\nClient send:%s",buffer);
						if(!strcmp(buffer,"exit"))
						{
							printf("\n Client requesting for closing connection");
							quit1=0;
						}
						if(!strcmp(buffer,"quit"))
						{
							quit1=0;
							quit=0;
						}
					}
				}
				printf("\nClosing client socket");
				SDLNet_TCP_Close(client_socket);
			}
		}
		quit1=1; //so that this thread can be used again
		temp_thread->status=0;
		push_thread(temp_thread);
	}// here it ends 
	printf("\n Terminating thread"); //TODO 
}
void TCP_NetClient::recvThreadFunc(TCP_NetClient * cli)
{
	for (;;) {
		char header[TCP_HEADER_SIZE];
		if (!receiveOnSocket(cli->mySocket, header, sizeof(header))) {
			break;
		}

		ulong playerId = SDLNet_Read32(header);
		ulong msgDataLen = SDLNet_Read32(header + 4);
		InternalMsg * msg = new InternalMsg(msgDataLen, playerId);
		if (msg == NULL || msg->buffer == NULL) {
			ERRORLOG("Failure to allocate memory for message");
			break;
		}

		if (!receiveOnSocket(cli->mySocket, msg->buffer, msgDataLen)) {
			delete msg;
			break;
		}

		cli->addIntMessage(msg);
	}
}
示例#21
0
static bool TryParseSyn(UDPpacket *packet, void *data)
{
	if (packet->len != sizeof(NetMsgSyn))
	{
		printf("Error: expected SYN, received packet len %d\n",
			packet->len);
		return false;
	}
	NetMsgSyn *msg = (NetMsgSyn *)packet->data;
	NetInputChannel *n = data;
	n->ack = SDLNet_Read16(&msg->seq) + 1;
	n->otherHost = SDLNet_Read32(&packet->address.host);
	n->otherPort = SDLNet_Read16(&packet->address.port);
	printf("Received SYN from %d.%d.%d.%d:%d\n",
		NET_IP_TO_CIDR_FORMAT(n->otherHost), n->otherPort);
	return true;
}
void ServerTCP::receiveMessages()
{
	while (!m_quit == 0)
	{
		//printf("...\n");
		/* This check the sd if there is a pending connection.
		* If there is one, accept that, and open a new socket for communicating */
		if ((m_clientSocketDescriptor = SDLNet_TCP_Accept(m_socketDescriptor)))
		{
			/* Now we can communicate with the client using csd socket
			* sd will remain opened waiting other connections */

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

			// IF A MESSAGE WAS RECEIVED

			if (SDLNet_TCP_Recv(m_clientSocketDescriptor, m_buffer, sizeof(m_buffer)) > 0)
			{

				memcpy(m_serverPackage->data, m_buffer, sizeof(Package));

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

			/* Close the client socket */
			close(m_clientSocketDescriptor);
			//assert(close(m_clientSocketDescriptor));
		}
	}
	
}
示例#23
0
bool TCPConnectionServer::SetServerSocket()
{
	IPaddress* ipRemote = SDLNet_TCP_GetPeerAddress( serverSocket[ serverSocket.size() - 1] );

	if ( ipRemote == nullptr )
	{
		std::cout  << "TCPConnection.cpp@" << __LINE__
			<< " Failed to get peer addres : " << hostName << " : " << portNr
			<< "\n\tServer : " << std::boolalpha << isServer << std::endl;
		return false;
	}

	std::cout << "TCPConnection.cpp@" << __LINE__
		<< " Host connected : "
		<< SDLNet_Read32( &ipRemote->host )
		<< " : " << SDLNet_Read16( &ipRemote->port ) << std::endl;

	return true;
}
示例#24
0
// Build an action from a network packet
Action::Action(const char *buffer, DistantComputer* _creator)
{
  m_creator = _creator;

  m_header.len = SDLNet_Read32(const_cast<char*>(buffer));
  ASSERT(m_header.len >= sizeof(Header));
  buffer += 4;
  // All of the following could be skipped for the actions we now,
  // for instance ACTION_GAME_CALCULATE_FRAME_PACKED
  m_header.type = buffer[0];
  buffer++;

  m_header.len -= sizeof(Header);
  m_bufsize = m_header.len;
  if (m_header.len) {
    m_read = m_write = m_var = (uint8_t*)malloc(m_bufsize);
    memcpy(m_var, buffer, m_bufsize);
  } else {
    m_read = m_write = m_var = NULL;
  }
}
void CNetManager::_CleanupClient()
{
	if(_client)
	{
		Uint32 otherIPAddr;
		bool wasConnected = false;
		if(Connected())
		{
			otherIPAddr = _client->getIpAddress().GetHostAddr();
			wasConnected = true;
		}

		delete _client;
		_client = NULL;

		if(wasConnected)
		{
			log << WARN << "Socket with  "<< SDLNet_Read32(&otherIPAddr) << " closed" << endl;
		}
	}
	if(!remoteCharactersMap.empty())
	{
		std::map<std::string, CCharacterObject*>::iterator iter;
		
		for(iter = remoteCharactersMap.begin(); iter != remoteCharactersMap.end(); iter++)
		{
			(*iter).second->FlagImageForRemoval();
			
			/* Todo: delete the images, but must be done AFTER */
			/* the image is removed from the renderlist		   */
			/*if((*iter).second)
			{
				delete (*iter).second;
				(*iter).second = 0;
			}*/
		}
		
	}
}
示例#26
0
void* serverstart(void* ptr){
  server* myserver = (server*)ptr;
  printf("Starting http-server on thread %d\n", pthread_self());
  if (SDLNet_Init() < 0) printf("Init SDL_Net");
  if (SDLNet_ResolveHost(&myserver->ip, NULL, 80) < 0) printf("Resolving host");
  if (!(myserver->socket = SDLNet_TCP_Open(&myserver->ip))) printf("Opening port (already in use?)");
  myserver->numsessions=0;
  myserver->clients=SDLNet_AllocSocketSet(1000);
  if(!myserver->clients) printf("SDLNet_AllocSocketSet failed\n");
  printf("myserver started port: %d\n", SDLNet_Read16(&myserver->ip.port));
  while(myserver->running){
    TCPsocket socket;
    IPaddress *ip;
    if ((socket = SDLNet_TCP_Accept(myserver->socket))){
      if ((ip = SDLNet_TCP_GetPeerAddress(socket))){
        printf("Client connected: %x %d\n", SDLNet_Read32(&(ip->host)), SDLNet_Read16(&(ip->port)));
      }else{
        printf("SDLNet_TCP_GetPeerAddress: %s\n", SDLNet_GetError());
      }
    }
  }
  pthread_exit((void*) 0);
}
示例#27
0
文件: i_net.c 项目: AlexMax/winmbf
unsigned long net_to_host32(unsigned int value)
{
  unsigned long l = value;

  return SDLNet_Read32(&l);
}
示例#28
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);
}
示例#29
0
float MovePacket::GetAngle() const
{
	return Uint32toFloat( SDLNet_Read32( &data_[22] ) );
}
示例#30
0
Uint32 MovePacket::GetTime() const
{
	return SDLNet_Read32( &data_[2] );
}