Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Changeset 9656 in orxonox.OLD for trunk/src/lib/network/network_stream.cc


Ignore:
Timestamp:
Aug 4, 2006, 11:01:28 PM (18 years ago)
Author:
bensch
Message:

orxonox/trunk: merged the proxy bache back with no conflicts

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/lib/network/network_stream.cc

    r9494 r9656  
    1111### File Specific:
    1212   main-programmer: Christoph Renner rennerc@ee.ethz.ch
    13    co-programmer:   Patrick Boenzli  boenzlip@orxonox.ethz.ch
     13   co-programmer:   Patrick Boenzli  patrick@orxonox.ethz.ch
    1414
    1515     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
    16      July 2006: some code rearangement and integration of the proxy server mechanism (boenzlip@ee.ethz.ch)
     16     July 2006: some code rearangement and integration of the proxy server mechanism (patrick@orxonox.ethz.ch)
    1717*/
    1818
     
    2020#define DEBUG_MODULE_NETWORK
    2121
     22#include "proxy/proxy_control.h"
    2223
    2324#include "base_object.h"
     
    8081      // init the shared network data
    8182      SharedNetworkData::getInstance()->setHostID(NET_ID_MASTER_SERVER);
     83      this->pInfo->userId = NET_ID_MASTER_SERVER;
     84      this->pInfo->nodeType = NET_MASTER_SERVER;
     85
    8286      break;
    8387    case NET_PROXY_SERVER_ACTIVE:
    8488      // init the shared network data
    8589      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
     90      this->pInfo->nodeType = NET_PROXY_SERVER_ACTIVE;
     91
    8692      break;
    8793    case NET_PROXY_SERVER_PASSIVE:
    8894      // init the shared network data
    8995      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
     96      this->pInfo->nodeType = NET_PROXY_SERVER_PASSIVE;
     97
    9098      break;
    9199    case NET_CLIENT:
    92100      SharedNetworkData::getInstance()->setHostID(NET_ID_UNASSIGNED);
     101      this->pInfo->nodeType = NET_CLIENT;
    93102      break;
    94103  }
     
    97106
    98107  // get the local ip address
    99   IPaddress ip;
    100   SDLNet_ResolveHost( &ip, NULL, 0);
     108  IP ip("localhost", 0);
    101109  this->pInfo->ip = ip;
    102110}
     
    112120  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
    113121  this->clientSocket = NULL;
     122  this->clientSoftSocket = NULL;
    114123  this->proxySocket = NULL;
    115124  this->networkGameManager = NULL;
     
    117126
    118127  this->pInfo = new PeerInfo();
    119   this->pInfo->userId = 0;
     128  this->pInfo->userId = NET_UID_UNASSIGNED;
    120129  this->pInfo->lastAckedState = 0;
    121130  this->pInfo->lastRecvedState = 0;
     131  this->pInfo->bLocal = true;
    122132
    123133  this->bRedirect = false;
    124134
    125135  this->currentState = 0;
     136  this->redirectionUID = NET_ID_MASTER_SERVER;
    126137
    127138  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
     
    142153  if ( this->clientSocket )
    143154  {
    144     clientSocket->close();
    145     delete clientSocket;
    146     clientSocket = NULL;
     155    this->clientSocket->close();
     156    delete this->clientSocket;
     157    this->clientSocket = NULL;
     158  }
     159  if ( this->clientSoftSocket )
     160  {
     161    this->clientSoftSocket->close();
     162    delete this->clientSoftSocket;
     163    this->clientSoftSocket = NULL;
    147164  }
    148165  if ( this->proxySocket)
     
    199216  this->peers[node].connectionMonitor = new ConnectionMonitor( NET_ID_MASTER_SERVER );
    200217  this->peers[node].ip = this->peers[node].socket->getRemoteAddress();
     218  this->peers[node].bLocal = true;
    201219}
    202220
     
    218236  this->peers[proxyId].connectionMonitor = new ConnectionMonitor( proxyId );
    219237  this->peers[proxyId].ip = this->peers[proxyId].socket->getRemoteAddress();
     238  this->peers[proxyId].bLocal = true;
    220239}
    221240
     
    225244 * @param port: interface port for all clients
    226245 */
    227 void NetworkStream::createServer(int clientPort, int proxyPort)
     246void NetworkStream::createServer(int clientPort, int proxyPort, int clientSoftPort)
    228247{
    229248  PRINTF(0)(" Creating new Server: listening for clients on port %i and for proxies on port %i", clientPort, proxyPort);
    230249  this->clientSocket= new UdpServerSocket(clientPort);
     250  this->clientSoftSocket= new UdpServerSocket(clientSoftPort);
    231251  this->proxySocket = new UdpServerSocket(proxyPort);
    232252}
     
    255275  Handshake* hs = new Handshake(this->pInfo->nodeType);
    256276  // fake the unique id
    257   hs->setUniqueID( NET_UID_HANDSHAKE );
    258   assert( peers[userId].handshake == NULL );
    259   peers[userId].handshake = hs;
     277  hs->setUniqueID( userId);
     278  assert( this->peers[userId].handshake == NULL );
     279  this->peers[userId].handshake = hs;
     280  this->peers[userId].bLocal = true;
    260281
    261282  // set the preferred nick name
     
    301322  // create the network monitor after all the init work and before there is any connection handlings
    302323  if( this->networkMonitor == NULL)
     324  {
    303325    this->networkMonitor = new NetworkMonitor(this);
     326    SharedNetworkData::getInstance()->setNetworkMonitor( this->networkMonitor);
     327  }
    304328
    305329
     
    318342    if ( this->clientSocket )
    319343      this->clientSocket->update();
     344    if ( this->clientSoftSocket)
     345      this->clientSoftSocket->update();
    320346    if( this->proxySocket)
    321347      this->proxySocket->update();
     
    328354    if ( this->clientSocket )
    329355      this->clientSocket->update();
     356    if ( this->clientSoftSocket)
     357      this->clientSoftSocket->update();
    330358    if( this->proxySocket)
    331359      this->proxySocket->update();
     
    348376    if( this->bRedirect)
    349377    {
    350       this->handleReconnect( NET_ID_MASTER_SERVER);
     378      this->handleReconnect( this->redirectionUID);
    351379    }
    352380  }
     
    362390  this->handleDownstream( tick );
    363391  this->handleUpstream( tick );
     392
     393  // process the local data of the message manager
     394  MessageManager::getInstance()->processData();
     395
     396  if( this->bSoftRedirect)
     397    this->softReconnectToServer(0, IP("localhost", 10001));
    364398}
    365399
     
    385419    if ( tempNetworkSocket )
    386420    {
    387       // determine the network node id
    388       if ( freeSocketSlots.size() > 0 )
     421      // get a userId
     422//       if ( freeSocketSlots.size() > 0 )
     423//       {
     424//         // this should never be called
     425//         userId = freeSocketSlots.back();
     426//         freeSocketSlots.pop_back();
     427//       }
     428//       else
    389429      {
    390         userId = freeSocketSlots.back();
    391         freeSocketSlots.pop_back();
    392       }
    393       else
    394       {
    395         userId = 1;
     430        // each server (proxy and master) have an address space for new network nodes of 1000 nodes
     431        // the first NET_ID_PROXY_MAX are always reserved for proxy servers
     432        userId = SharedNetworkData::getInstance()->getHostID() * 1000 + NET_ID_PROXY_MAX + 1;
    396433
    397434        for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
    398435          if ( it->first >= userId )
    399436            userId = it->first + 1;
     437
     438        // make sure that this server only uses an address space of 1000
     439        assert( userId < (SharedNetworkData::getInstance()->getHostID() + 1) * 1000);
    400440      }
    401441      // this creates a new entry in the peers list
     
    410450  }
    411451
     452  if( this->clientSoftSocket != NULL)
     453  {
     454    tempNetworkSocket = this->clientSoftSocket->getNewSocket();
     455
     456    // we got new NET_CLIENT connecting
     457    if ( tempNetworkSocket )
     458    {
     459
     460      // this creates a new entry in the peers list
     461      peers[userId].socket = tempNetworkSocket;
     462      peers[userId].nodeType = NET_CLIENT;
     463
     464      // handle the newly connected client
     465      this->handleSoftConnect(userId);
     466
     467      PRINTF(0)("New Client softly connected: %d :D\n", userId);
     468    }
     469  }
     470
    412471
    413472  if( this->proxySocket != NULL)
     
    419478    {
    420479      // determine the network node id
    421       if ( freeSocketSlots.size() > 0 )
    422       {
    423         userId = freeSocketSlots.back();
    424         freeSocketSlots.pop_back();
    425       }
    426       else
     480//       if ( freeSocketSlots.size() > 0 )
     481//       {
     482//         userId = freeSocketSlots.back();
     483//         freeSocketSlots.pop_back();
     484//       }
     485//       else
    427486      {
    428487        userId = 1;
    429488
    430         for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
    431           if ( it->first >= userId )
    432             userId = it->first + 1;
     489        // find an empty slot within the range
     490        for( int i = 0; i < NET_ID_PROXY_MAX; i++)
     491        {
     492          if( this->peers.find( i) == this->peers.end())
     493          {
     494            userId = i;
     495            break;
     496          }
     497        }
     498
     499//         for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
     500//           if ( it->first >= userId )
     501//             userId = it->first + 1;
    433502      }
    434503
     
    443512    }
    444513  }
     514
    445515
    446516
     
    461531      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
    462532
     533
    463534      this->handleDisconnect( it->second.userId);
     535
     536      if( SharedNetworkData::getInstance()->isProxyServerActive())
     537        ProxyControl::getInstance()->signalLeaveClient(it->second.userId);
    464538
    465539      it++;
     
    469543    it++;
    470544  }
    471 
    472 
    473545}
    474546
     
    481553{
    482554  // create new handshake and init its variables
    483   peers[userId].handshake = new Handshake(this->pInfo->nodeType, userId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
    484   peers[userId].handshake->setUniqueID(userId);
    485 
    486   peers[userId].connectionMonitor = new ConnectionMonitor( userId );
    487   peers[userId].userId = userId;
     555  this->peers[userId].handshake = new Handshake(this->pInfo->nodeType, userId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
     556  this->peers[userId].handshake->setUniqueID(userId);
     557
     558  this->peers[userId].connectionMonitor = new ConnectionMonitor( userId );
     559  this->peers[userId].userId = userId;
     560  this->peers[userId].bLocal = true;
    488561
    489562  PRINTF(0)("num sync: %d\n", synchronizeables.size());
     
    494567  if( pi != NULL)
    495568  {
    496     peers[userId].handshake->setProxy1Address( pi->ip);
     569    this->peers[userId].handshake->setProxy1Address( pi->ip);
    497570  }
    498571  pi = this->networkMonitor->getSecondChoiceProxy();
    499572  if( pi != NULL)
    500     peers[userId].handshake->setProxy2Address( pi->ip);
     573    this->peers[userId].handshake->setProxy2Address( pi->ip);
    501574
    502575  // check if the connecting client should reconnect to a proxy server
    503576  if( SharedNetworkData::getInstance()->isMasterServer())
    504     peers[userId].handshake->setRedirect(/*this->networkMonitor->isReconnectNextClient()*/false);
     577  {
     578    if( this->networkMonitor->isReconnectNextClient())
     579    {
     580      this->peers[userId].handshake->setRedirect(true);
     581      PRINTF(0)("forwarding client to proxy server because this server is saturated\n");
     582    }
     583  }
    505584
    506585  // the connecting node of course is a client
    507   peers[userId].ip = peers[userId].socket->getRemoteAddress();
    508 }
     586  this->peers[userId].ip = this->peers[userId].socket->getRemoteAddress();
     587}
     588
     589
     590/**
     591 * this handles new soft connections
     592 * @param userId: the id of the new user node
     593 *
     594 * soft connections are connections from clients that are already in the network and don't need a new handshake etc.
     595 * the state of all entitites owned by userId are not deleted and stay
     596 * soft connections can not be redirected therefore they are negotiated between the to parties
     597 */
     598void NetworkStream::handleSoftConnect( int userId)
     599{
     600  // create new handshake and init its variables
     601  this->peers[userId].handshake = NULL;
     602  this->peers[userId].handshake->setUniqueID(userId);
     603
     604  this->peers[userId].connectionMonitor = new ConnectionMonitor( userId );
     605  this->peers[userId].userId = userId;
     606  this->peers[userId].bLocal = true;
     607
     608  PRINTF(0)("num sync: %d\n", synchronizeables.size());
     609
     610  // the connecting node of course is a client
     611  this->peers[userId].ip = this->peers[userId].socket->getRemoteAddress();
     612}
     613
    509614
    510615
     
    524629    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
    525630  }
     631
     632  PRINT(0)(" Current number of connections is: %i\n", this->peers.size());
     633  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
     634  {
     635    PRINT(0)("  peers[%i] with uniqueId %i and address: %s\n", it->first, it->second.userId, it->second.ip.ipString().c_str());
     636  }
     637  PRINT(0)("\n\n");
     638
    526639
    527640  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
     
    576689            // - client       <==> master server
    577690            // - proxy server <==> master server
    578             if(  SharedNetworkData::getInstance()->isClient() || SharedNetworkData::getInstance()->isProxyServerActive() && it->second.isMasterServer())
     691            if(  SharedNetworkData::getInstance()->isClient() ||
     692                 SharedNetworkData::getInstance()->isProxyServerActive() &&
     693                 SharedNetworkData::getInstance()->isUserMasterServer(it->second.userId))
    579694            {
    580               PRINTF(0)("Handshake: i am in client role\n");
     695              PRINTF(4)("Handshake: i am in client role\n");
    581696
    582697              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
    583698              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
    584699
    585 #warning the ip address is not set here because it results in a segfault when connecting to a proxy server => trace this later
    586700//               it->second.ip = it->second.socket->getRemoteAddress();
    587701
    588               // it->second.nodeType = it->second.handshake->getRemoteNodeType();
     702              it->second.nodeType = it->second.handshake->getRemoteNodeType();
    589703              // it->second.ip = it->second.socket->getRemoteAddress();
    590704              // add the new server to the nodes list (it can be a NET_MASTER_SERVER or NET_PROXY_SERVER)
     
    633747              else if ( SharedNetworkData::getInstance()->isProxyServerActive() && it->second.isClient() )
    634748              {
    635                 PRINTF(0)("Handshake: i am in server role\n");
     749                PRINTF(4)("Handshake: Proxy in server role: connecting %i\n", it->second.userId);
    636750
    637751                it->second.ip = it->second.socket->getRemoteAddress();
     
    639753                this->networkMonitor->addNode(&it->second);
    640754
    641                 this->handleNewClient( it->second.userId );
     755                // work with the ProxyControl to init the new client
     756                ProxyControl::getInstance()->signalNewClient( it->second.userId);
    642757
    643758                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
     
    667782/**
    668783 * this functions handles a reconnect event received from the a NET_MASTER_SERVER or NET_PROXY_SERVER
     784 * @param userId
    669785 */
    670786void NetworkStream::handleReconnect(int userId)
    671787{
    672788  this->bRedirect = false;
     789#warning this peer will be created if it does not yet exist: dangerous
    673790  PeerInfo* pInfo = &this->peers[userId];
     791
     792  IP proxyIP;
     793  if( this->networkMonitor->isForcedReconnection())
     794    proxyIP = this->networkMonitor->getForcedReconnectionIP();
     795  else
     796    proxyIP = pInfo->handshake->getProxy1Address();
    674797
    675798  PRINTF(0)("===============================================\n");
    676799  PRINTF(0)("Client is redirected to the other proxy servers\n");
    677800  PRINTF(0)("  user id: %i\n", userId);
    678   PRINTF(0)("  connecting to: %s\n", this->networkMonitor->getFirstChoiceProxy()->ip.ipString().c_str());
     801  PRINTF(0)("  connecting to: %s\n", proxyIP.ipString().c_str());
    679802  PRINTF(0)("===============================================\n");
    680803
     
    683806  pInfo->lastRecvedState = 0;
    684807
    685   // temp save the ip address here
    686   IP proxyIP = pInfo->handshake->getProxy1Address();
    687 
    688808  // disconnect from the current server and reconnect to proxy server
    689809  this->handleDisconnect( userId);
    690810  this->connectToProxyServer(NET_ID_PROXY_SERVER_01, proxyIP.ipString(), 9999);
     811//   this->connectToMasterServer(proxyIP.ipString(), 9999);
    691812  #warning the ports are not yet integrated correctly in the ip class
    692813
     
    696817
    697818
     819
     820/**
     821 * reconnects to another server, with full handshake
     822 * @param address of the new server
     823 */
     824void NetworkStream::reconnectToServer(IP address)
     825{
     826  ///TODO make a redirection struct and push it to the network monitor
     827  this->networkMonitor->setForcedReconnection(address);
     828
     829  // reconnect (depending on how we are connected at the moment)
     830  if ( peers.find( NET_ID_MASTER_SERVER) != peers.end() )
     831    this->redirectionUID = NET_ID_MASTER_SERVER;
     832  else if( peers.find( NET_ID_PROXY_SERVER_01) != peers.end() )
     833    this->redirectionUID = NET_ID_PROXY_SERVER_01;
     834
     835  this->bRedirect = true;
     836}
     837
     838
     839
     840/**
     841 * softly reconnecting to another server
     842 * @param serverUserId the id of the client
     843 * @param address  of the new server
     844 */
     845void NetworkStream::softReconnectToServer(int serverUserId, IP address)
     846{
     847//   this->networkMonitor->setForcedReconnection(address);
     848//   this->handleReconnect( NET_ID_MASTER_SERVER);
     849
     850  // create the new udp socket and open the connection to the soft connection port
     851  NetworkSocket* newSocket = new UdpSocket(address.ipString(), 10001);
     852
     853  // delete the synchronization state of this client for all syncs
     854  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
     855    (*it2)->cleanUpUser( serverUserId );
     856  }
     857
     858  // temp save the old socket
     859  NetworkSocket* oldSocket = this->peers[serverUserId].socket;
     860
     861  // now integrate the new socket
     862  this->peers[serverUserId].socket = newSocket;
     863
     864  this->bSoftRedirect = false;
     865  return;
     866
     867  // now remove the old socket
     868  oldSocket->disconnectServer();
     869  delete oldSocket;
     870
     871  // replace the old connection monitor
     872  if ( this->peers[serverUserId].connectionMonitor )
     873    delete this->peers[serverUserId].connectionMonitor;
     874  this->peers[serverUserId].connectionMonitor = new ConnectionMonitor(serverUserId);
     875
     876  // remove old node from the network monitor
     877  this->networkMonitor->removeNode(&this->peers[serverUserId]);
     878
     879}
     880
     881
     882
     883/**
     884 * prepares a soft connection for a client to connect to
     885 * @param userId that will connect to this server
     886 */
     887void NetworkStream::prepareSoftConnection(int userId)
     888{
     889  PRINTF(0)("prepare soft connection for userId %i\n");
     890}
     891
     892
     893
    698894/**
    699895 * handles the disconnect event
     
    702898void NetworkStream::handleDisconnect( int userId )
    703899{
    704   peers[userId].socket->disconnectServer();
    705   delete peers[userId].socket;
    706   peers[userId].socket = NULL;
    707 
    708   if ( peers[userId].handshake )
    709     delete peers[userId].handshake;
    710   peers[userId].handshake = NULL;
    711 
    712   if ( peers[userId].connectionMonitor )
    713     delete peers[userId].connectionMonitor;
    714   peers[userId].connectionMonitor = NULL;
    715 
    716 
     900  this->peers[userId].socket->disconnectServer();
     901  delete this->peers[userId].socket;
     902  this->peers[userId].socket = NULL;
     903
     904  if ( this->peers[userId].handshake )
     905    delete this->peers[userId].handshake;
     906  this->peers[userId].handshake = NULL;
     907
     908  if ( this->peers[userId].connectionMonitor )
     909    delete this->peers[userId].connectionMonitor;
     910  this->peers[userId].connectionMonitor = NULL;
     911
     912  // delete the synchronization state of this client for all syncs
    717913  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
    718914    (*it2)->cleanUpUser( userId );
     
    724920  this->freeSocketSlots.push_back( userId );
    725921
    726   peers.erase( userId);
    727 }
    728 
     922  this->networkMonitor->removeNode(&this->peers[userId]);
     923  this->peers.erase( userId);
     924}
    729925
    730926
     
    793989      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
    794990
    795       // server fakes uniqueid == 0 for handshake
     991      // server fakes uniqueid == 0 for handshake synchronizeable
    796992      if ( ( SharedNetworkData::getInstance()->isMasterServer() ||
    797993             SharedNetworkData::getInstance()->isProxyServerActive() &&  peer->second.isClient() ) &&
    798              sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1) // plus one to handle one client more than the max to redirect it
     994             ( sync.getUniqueID() >= 1000 || sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1 + NET_ID_PROXY_MAX))
    799995        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
    800996      else
     
    9301126      while ( offset + 2 * INTSIZE < length )
    9311127      {
     1128        // read the unique id of the sync
    9321129        assert( offset > 0 );
    9331130        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
    9341131        offset += INTSIZE;
    9351132
     1133        // read the data length
    9361134        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
    9371135        offset += INTSIZE;
     
    9451143        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
    9461144        {
    947           // client thinks his handshake has id 0!!!!!
    948           if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
     1145          // client thinks his handshake has a special id: hostId * 1000 (host id of this server)
     1146          if ( (*it)->getUniqueID() == uniqueId ||                                          // so this client exists already go to sync work
     1147                 ( uniqueId == 0  && (*it)->getUniqueID() == peer->second.userId ) )        // so this is a Handshake!
    9491148          {
    9501149            sync = *it;
Note: See TracChangeset for help on using the changeset viewer.