void accept_connections() { if (SDLNet_SocketReady(serversock)) { TCPsocket client = SDLNet_TCP_Accept(serversock); if (client) { clients.push_back(new ClientConnection(clients.size()+1, client)); std::stringstream out; out << "version 0" << std::endl; out << "your_id " << clients.size() << std::endl; std::string str = out.str(); SDLNet_TCP_Send(client, const_cast<char*>(str.c_str()), str.length()+1); IPaddress* ip = SDLNet_TCP_GetPeerAddress(client); const char* host; if((host = SDLNet_ResolveIP(ip)) != 0) std::cout << "# Got client connection from " << host << " " << ip->port << std::endl; else std::cout << "# Got client connection from " << ip->host << " " << ip->port << std::endl; int numused = SDLNet_TCP_AddSocket(socketset, client); if (numused == -1) { printf("SDLNet_AddSocket: %s\n", SDLNet_GetError()); // perhaps you need to restart the set and make it bigger... } else { std::cout << "# Sockets used: " << numused << std::endl; } } } }
int game_host::waitForClient_test() { cout << "waiting for first player to connect...\n"; while(!(player1sd = SDLNet_TCP_Accept(sd))) //wait for first connection, with 50ms delay to keep CPU down SDL_Delay(50); string ipMess = ""; while(SDLNet_UDP_Recv(p1UDPsock, UDPpack1) == 0) SDL_Delay(5); SDLNet_UDP_Bind(p1UDPsock,10,&(UDPpack1->address)); cout << this->recieveMessagep1() << "\n"; //on successful connect, client sends a message SDLNet_TCP_AddSocket(socketset, player1sd); //could error check here this->player1ip = SDLNet_TCP_GetPeerAddress(player1sd); //SDLNet_ResolveHost(&(UDPpack1->address), cl.c_str(), port); //player2ip->host = SDLNet_TCP_GetPeerAddress(player1sd)->host; //player2ip->port = port; //UDPpack1->address = *player1ip; sendtoP1_test("1SIG:START"); cout << "client connected, continuing...\n"; return 1; }
ClientConnection::ClientConnection(TCPsocket sock, ClientManager *manager) : socket(sock), status(0), manager(manager) { printf("ClientConnection()\n"); bindings[SDLK_LEFT] = bindings[SDLK_a] = Binding(&Entity::left, 200); bindings[SDLK_RIGHT] = bindings[SDLK_d] = Binding(&Entity::right, 200); bindings[SDLK_UP] = bindings[SDLK_w] = Binding(&Entity::up, 200); bindings[SDLK_DOWN] = bindings[SDLK_s] = Binding(&Entity::down, 200); bindings[SDLK_SPACE] = bindings[SDLK_e] = Binding(&Entity::prepare_action, &Entity::action); bindings[SDLK_LSHIFT]= bindings[SDLK_f] = Binding(&Entity::prepare_grab, &Entity::grab); bindings[SDLK_LCTRL] = bindings[SDLK_g] = Binding(&Entity::prepare_drop, &Entity::drop); bindings[SDLK_LALT] = bindings[SDLK_q] = Binding(&Entity::prepare_swap, &Entity::swap); name = SDLNet_ResolveIP(SDLNet_TCP_GetPeerAddress(socket)); update_entity_connection(); old_x = get_x(); old_y = get_y(); send_mutex = SDL_CreateMutex(); messages_mutex = SDL_CreateMutex(); send_thread = SDL_CreateThread(send_thread_func, this); recieve_thread = SDL_CreateThread(recieve_thread_func, this); char data[] = { 'b', 151, 130, 42 }; // set background int len = sizeof(data); send(data, len); }
void Connection::setSocket(const TCPsocket& newUserSocket){ ScopedMutexLock(pimpl_->dataAccess); pimpl_->userSocket = newUserSocket; pimpl_->peer = SDLNet_TCP_GetPeerAddress(pimpl_->userSocket); pimpl_->active = true; pimpl_->connectTime = SDL_GetTicks(); }
void NetworkThread::__run__() { TCPsocket csd; IPaddress* remoteIP; bool quit = false; while (!quit) { std::cout << "<<<<<<<<<<<<< Server::waitForConnection() - WAITING..." << std::endl; SDL_Delay(1000); //emit testSignal(); //quit = true; /* 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 */ //std::cout << "<<<<<<<<<<<<< Host connected: " << SDLNet_Read32(&remoteIP->host) << " port: " << SDLNet_Read16(&remoteIP->port) << std::endl; //std::cout << "<<<<<<<<<<<<< Host connected: " << remoteIP->host << " port: " << remoteIP->port << std::endl; //clientVector.push_back(&csd); clientSocketList->addClient(csd); emit newNetworkConnection("<b>[NET]</b> A new Client connected<br>"); } else { std::cout << "<<<<<<<<<<<<< SDLNet_TCP_GetPeerAddress: " << SDLNet_GetError() << std::endl; } } } }
void new_connection(TCPsocket sock) { TCPsocket tmp; struct socket_node *socket; IPaddress *ip; /* accept the connection temporarily */ tmp = SDLNet_TCP_Accept(sock); if (!tmp) do_error(SDLNet_GetError()); /* are we full or game already started? */ if (get_active_players() + 1 > NUM_PLAYERS || current_turn) SDLNet_TCP_Close(tmp); else { /* nope! */ socket = new_socket(SOCKET_CLIENT); socket->sock = tmp; if (SDLNet_TCP_AddSocket(sockset, tmp) < 0) do_error(SDLNet_GetError()); ip = SDLNet_TCP_GetPeerAddress(tmp); if (!ip) do_error(SDLNet_GetError()); if (SDLNet_ResolveIP(ip)) strcpy(socket->host, SDLNet_ResolveIP(ip)); else sprintf(socket->host, "Unknown IP"); join_player(socket); /* add player to game */ } }
int Connection::connect(const std::string &host, int port){ if( (port == 0) || isSpace(host) ){ std::cerr << __FILE__ << " " << __LINE__ << ": " << "Connection::connect(string, int): Port can't be 0. Host can't be whitespace." << std::endl; return -1; } IPaddress ip; if( SDLNet_ResolveHost(&ip, host.c_str(), port) == -1 ){ std::cerr << __FILE__ << " " << __LINE__ << ": " << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl; return -1; } ScopedMutexLock(pimpl_->dataAccess); //make sure is dissconected if( pimpl_->userSocket != NULL ){ SDLNet_TCP_Close( pimpl_->userSocket ); pimpl_->userSocket = NULL; } pimpl_->userSocket = SDLNet_TCP_Open(&ip); if( pimpl_->userSocket == NULL ){ std::cerr << __FILE__ << " " << __LINE__ << ": " << "SDLNet_TCP_Open: " << SDLNet_GetError() << std::endl; pimpl_->active = false; pimpl_->connectTime = 0; return -1; } pimpl_->peer = SDLNet_TCP_GetPeerAddress(pimpl_->userSocket); pimpl_->active = true; pimpl_->connectTime = SDL_GetTicks(); return 1; }
/*接続*/ void connection_connect(CONNECTION_DATA* con){ /*変数宣言*/ TCPsocket *sock = &con->socket; char* str; int content_length = -1; int is_err = false; FILE* log_file; /*接続先IPを取得*/ con->ip = SDLNet_TCP_GetPeerAddress(*sock); /*ビジー状態に設定*/ if(!lock_connection(con)){ SDLNet_TCP_Close(*sock); return; } /*ヘッダを判断する*/ str = NetUtl_readLine(sock); if(str == null){ /*通信終わり*/ SDLNet_TCP_Close(*sock); /*接続終了フラグ*/ unlock_connection(con); return; } if(strncmp(str,POST_HEADER,strlen(POST_HEADER)) != 0){ is_err = true; } /*とりあえず最後まで受信する。*/ if(is_err){//エラー /*ログに追加*/ log_file = lock_log_file(); time_output(); ip_output(con->ip); fprintf(log_file,"%s\n",str); unlock_log_file(); //最後まで受信するだけ while(*(str = NetUtl_readLine(sock)) != END_CHAR){ } }else{//ヘッダを取得する while(*(str = NetUtl_readLine(sock)) != END_CHAR){ if(content_length < 0){ if(strncmp( str, CONTENT_LENGTH_HEADER, strlen(CONTENT_LENGTH_HEADER) ) == 0){ sscanf(str,CONTENT_LENGTH_HEADER_F,&content_length); } }//else if(){} } } if(!is_err && content_length >= 0){/*とりあえず通信するに値する*/ connection_do_request(con,content_length); }else{/*まったく関係ない*/ connection_send_error(sock); } /*通信終わり*/ SDLNet_TCP_Close(*sock); /*接続終了フラグ*/ unlock_connection(con); }
void CDataSocket::recalculateRemoteHost() { if (m_socket) { IPaddress* addr = SDLNet_TCP_GetPeerAddress(m_socket); m_remoteHost = getIp(addr->host); } }
void NetServer::handleserver() { int which; unsigned char data; TCPsocket newsock = SDLNet_TCP_Accept(tcpsock); if (newsock == NULL) return; /* Look for unconnected person slot */ for (which = 0; which < MAXCLIENTS; ++which) { if (!clients[which].sock) { break; } } if (which == MAXCLIENTS) { /* Look for inactive person slot */ for (which = 0; which < MAXCLIENTS; ++which) { if (clients[which].sock && !clients[which].active) { /* Kick them out.. */ data = NET_MSG_REJECT; SDLNet_TCP_Send(clients[which].sock, &data, 1); SDLNet_TCP_DelSocket(socketset, clients[which].sock); SDLNet_TCP_Close(clients[which].sock); numclients--; #ifdef _DEBUG printf("Killed inactive socket %d\n", which); #endif break; } } } if (which == MAXCLIENTS) { /* No more room... */ data = NET_MSG_REJECT; SDLNet_TCP_Send(newsock, &data, 1); SDLNet_TCP_Close(newsock); #ifdef _DEBUG printf("Connection refused -- server full\n"); #endif } else { /* Add socket as an inactive person */ clients[which].sock = newsock; clients[which].peer = *SDLNet_TCP_GetPeerAddress(newsock); SDLNet_TCP_AddSocket(socketset, clients[which].sock); numclients++; #ifdef _DEBUG printf("New inactive socket %d\n", which); #endif } }
Client::Client(TCPsocket * socket_){ socket = *socket_; msg = (char*) malloc(BUFFER_SIZE); ID = ++IDCounter; startPos = 0; recvSize = 0; mutex = SDL_CreateMutex(); address = (char*) malloc(24); address = (char*) getStringAddress(*SDLNet_TCP_GetPeerAddress(socket)); }
static __inline__ IPaddress *snTCPGetPeerAddress(TCPsocket s) { IPaddress *val = NULL; lockSDLNet(); val = SDLNet_TCP_GetPeerAddress(s); unlockSDLNet(); return val; }
/* * network_get_peer_address() - Return the IP data of the remote TCP connection * @tcp: the remote connection to return data for */ IPaddress* network_get_peer_address(TCPsocket* tcp) { IPaddress* ipa = nullptr; // Declare an IP data struct ipa = SDLNet_TCP_GetPeerAddress(*tcp); // Attempt to get the peer address info if (ipa == nullptr) { // If the information could not be retrieved std::cerr << "Failed to get TCP peer address: " << SDLNet_GetError() << "\n"; // Output the error message } return ipa; // Return the IP data on success }
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; }
int game_host::waitForClients() { cout << "waiting for first player to connect...\n"; while(!(player1sd = SDLNet_TCP_Accept(sd))) //wait for first connection, with 50ms delay to keep CPU down SDL_Delay(50); string ipMess = ""; while(SDLNet_UDP_Recv(p1UDPsock, UDPpack1) == 0) SDL_Delay(5); SDLNet_UDP_Bind(p1UDPsock,10,&(UDPpack1->address)); cout << this->recieveMessagep1() << "\n"; //client sends its IP SDLNet_TCP_AddSocket(socketset, player1sd); //could error check here this->player1ip = SDLNet_TCP_GetPeerAddress(player1sd); //UDPpack1->address.port = player1ip.port; //UDPpack1->address.host = player1ip.host; cout << "waiting for second player to connect...\n"; while(!(player2sd = SDLNet_TCP_Accept(sd))) SDL_Delay(50); while(!SDLNet_UDP_Recv(p1UDPsock, UDPpack2)) SDL_Delay(5); SDLNet_UDP_Bind(p1UDPsock,10,&(UDPpack2->address)); //cout << this->recieveMessagep2() << "\n"; SDLNet_TCP_AddSocket(socketset, player2sd); //could error check here as well player2ip = SDLNet_TCP_GetPeerAddress(player2sd); //UDPpack2->address.port = player2ip.port; //UDPpack2->address.host = player2ip.host; if(SDLNet_TCP_Send(player1sd, "1SIG:START", 16 /* buff.length()+1*/) < 16) { cout << "Message to client 1 failed to send...\n"; return -1; } if(SDLNet_TCP_Send(player2sd, "2SIG:START", 16 /*buff.length()+1*/) < 16) { cout << "Message to client 2 failed to send...\n"; return -1; } cout << "both clients connected, continuing...\n"; return 1; }
bool TCPClientSocket::GetRemoteAddressString(Bit8u* buffer) { IPaddress* remote_ip; Bit8u b1, b2, b3, b4; remote_ip=SDLNet_TCP_GetPeerAddress(mysock); if(!remote_ip) return false; b4=remote_ip->host>>24; b3=(remote_ip->host>>16)&0xff; b2=(remote_ip->host>>8)&0xff; b1=remote_ip->host&0xff; sprintf((char*)buffer,"%u.%u.%u.%u",b1,b2,b3,b4); return true; }
void HandleServer(void) { TCPsocket newsock; int which; unsigned char data; newsock = SDLNet_TCP_Accept(servsock); if ( newsock == NULL ) { return; } /* Look for unconnected person slot */ for ( which=0; which<CHAT_MAXPEOPLE; ++which ) { if ( ! people[which].sock ) { break; } } if ( which == CHAT_MAXPEOPLE ) { /* Look for inactive person slot */ for ( which=0; which<CHAT_MAXPEOPLE; ++which ) { if ( people[which].sock && ! people[which].active ) { /* Kick them out.. */ data = CHAT_BYE; SDLNet_TCP_Send(people[which].sock, &data, 1); SDLNet_TCP_DelSocket(socketset, people[which].sock); SDLNet_TCP_Close(people[which].sock); #ifdef DEBUG fprintf(stderr, "Killed inactive socket %d\n", which); #endif break; } } } if ( which == CHAT_MAXPEOPLE ) { /* No more room... */ data = CHAT_BYE; SDLNet_TCP_Send(newsock, &data, 1); SDLNet_TCP_Close(newsock); #ifdef DEBUG fprintf(stderr, "Connection refused -- chat room full\n"); #endif } else { /* Add socket as an inactive person */ people[which].sock = newsock; people[which].peer = *SDLNet_TCP_GetPeerAddress(newsock); SDLNet_TCP_AddSocket(socketset, people[which].sock); #ifdef DEBUG fprintf(stderr, "New inactive socket %d\n", which); #endif } }
void send( TCPsocket* sock, char type, const void* data, char len, bool outputAllowed ) { if ( *sock != NULL ) { IPaddress * clientIP = SDLNet_TCP_GetPeerAddress(*sock); if (outputAllowed) printf("Sending -> %s : (%c:%X) \"%s\"\n", getStringAddress(*clientIP), type, type, data); SDLNet_TCP_Send(*sock, &type,1); SDLNet_TCP_Send(*sock, &len, 1); SDLNet_TCP_Send(*sock, data, len); } }
/*/////////////////////////////////////////////////////////// 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 }
/** * @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; }
void TCPConnectionServer::GetServerInfo( std::string &str, uint32_t prt) { IPaddress* ipRemote = SDLNet_TCP_GetPeerAddress( serverSocket[ serverSocket.size() - 1] ); uint8_t* ptr = reinterpret_cast< uint8_t* > ( &ipRemote->host ); std::stringstream ss; ss << "IP : " << static_cast< int32_t > ( ptr[0] ) << "." << static_cast< int32_t > ( ptr[1] ) << "." << static_cast< int32_t > ( ptr[2] ) << "." << static_cast< int32_t > ( ptr[3] ); str = ss.str(); prt = SDLNet_Read16( &ipRemote->port ); }
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)); } } }
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; }
void acceptConnection() { int clientId; TCPsocket incomming; while (true) { incomming = SDLNet_TCP_Accept(TCPsock); if (incomming !=0x0) { if ((clientId = getClientId())<0) {printf("Too many users! \n");} else { clients[clientId].socket = incomming; clients[clientId].id = clientId; clients[clientId].active = true; clients[clientId].ip = SDLNet_TCP_GetPeerAddress(incomming)->host; SDL_DetachThread(SDL_CreateThread(Lobby, "lobbyThread", &clientId)); incomming = NULL; } } if(ClientsAreReady()) { printf("starting in 3...\n"); Broadcast("$4starting in 3..."); SDL_Delay(1000); if(ClientsAreReady()) { printf("starting in 2...\n"); Broadcast("$4starting in 2..."); SDL_Delay(1000); if(ClientsAreReady()) { printf("starting in 1...\n"); Broadcast("$4starting in 1..."); SDL_Delay(1000); printf("!GO\n"); Broadcast("!GO"); break; } } } incomming = NULL; SDL_Delay(1000); } }
/* wait for incoming connection */ int main(int argc,char**argv) { IPaddress ip,*remoteip; TCPsocket server,client; Uint32 ipaddr; Uint16 port; int len; char msg[1024]; if(SDL_Init(0)==-1) error("error sdl init"); if(SDLNet_Init()==-1) error("error sdlnet init"); port=12346; if(SDLNet_ResolveHost(&ip,NULL,port)==-1) error("resolvehost error"); /* open server socket */ if(!(server=SDLNet_TCP_Open(&ip))) error("couldn't open tcp"); while(1) { client=SDLNet_TCP_Accept(server); if(!client) { printf("waiting for connection\n"); SDL_Delay(200); continue; } remoteip=SDLNet_TCP_GetPeerAddress(client); if(!remoteip) error("error getting peer"); ipaddr=SDL_SwapBE32(remoteip->host); printf("accepted connection from %d.%d.%d.%d port %u\n", ipaddr>>24,(ipaddr>>16)&255,(ipaddr>>8)&255,ipaddr&255,remoteip->port); len=SDLNet_TCP_Recv(client,msg,1024); SDLNet_TCP_Close(client); if(!len) error("didn't receive msg"); printf("got: %s\n",msg); break; } SDLNet_Quit(); SDL_Quit(); return 0; }
int Connection::connect(IPaddress *ip){ if( ip == NULL ){ return -1; } ScopedMutexLock(pimpl_->dataAccess); //make sure is dissconected if( pimpl_->userSocket != NULL ){ SDLNet_TCP_Close( pimpl_->userSocket ); pimpl_->userSocket = NULL; } // connect to ip (if one is stored) pimpl_->userSocket = SDLNet_TCP_Open(ip); if( pimpl_->userSocket == NULL ){ std::cerr << __FILE__ << " " << __LINE__ << ": " << "SDLNet_TCP_Open: " << SDLNet_GetError() << std::endl; pimpl_->active = false; pimpl_->connectTime = 0; return -1; } pimpl_->peer = SDLNet_TCP_GetPeerAddress(pimpl_->userSocket); pimpl_->active = true; pimpl_->connectTime = SDL_GetTicks(); return 1; }
bool TCPConnection::SetServerSocket() { IPaddress* ipRemote = SDLNet_TCP_GetPeerAddress( serverSocket ); if ( ipRemote == nullptr ) { std::stringstream ss( "" ); ss << hostName << " : " << portNr << "\n\tServer : " << std::boolalpha << isServer; isConnected = false; logger->Log( __FILE__, __LINE__, " Failed to get peer addres : ", ss.str() ); return false; } std::stringstream ss(""); ss << ipRemote->host << " : " << ipRemote->port << std::endl; logger->Log( __FILE__, __LINE__, " Host connected : ", ss.str() ); isConnected = true; return true; }
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); }
int NetServer::NetServerThread( void *server ) { NetServer *net_server = (NetServer *) server; TCPsocket client_socket; IPaddress *remote_ip; while( net_server->Listening ) { // Check for new connections. if( (client_socket = SDLNet_TCP_Accept(net_server->Socket)) ) { ConnectedClient *connected_client = new ConnectedClient( client_socket, net_server->UseOutThreads, net_server->NetRate, net_server->Precision ); if( (remote_ip = SDLNet_TCP_GetPeerAddress(client_socket)) ) { connected_client->IP = Endian::ReadBig32(&(remote_ip->host)); connected_client->Port = Endian::ReadBig16(&(remote_ip->port)); char cstr[ 1024 ] = ""; snprintf( cstr, 1024, "Client connected: %i.%i.%i.%i:%i", (connected_client->IP & 0xFF000000) >> 24, (connected_client->IP & 0x00FF0000) >> 16, (connected_client->IP & 0x0000FF00) >> 8, connected_client->IP & 0x000000FF, connected_client->Port ); Raptor::Server->ConsolePrint( cstr ); } else {
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); }