Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Ignore:
Timestamp:
Mar 22, 2018, 4:12:23 PM (7 years ago)
Author:
mdedial
Message:

WIP 22.03.18: Begin documenting server-side code

Location:
code/branches/Masterserver_FS18/src/libraries/network
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • code/branches/Masterserver_FS18/src/libraries/network/Connection.cc

    r11071 r11829  
    4545  const unsigned int                NETWORK_DISCONNECT_TIMEOUT = 500;
    4646
     47  /**
     48   * Constructor
     49   * @param firstPeerId The initial value of nextPeerID_
     50   */
    4751  Connection::Connection(uint32_t firstPeerID):
    4852    host_(nullptr), bCommunicationThreadRunning_(false), nextPeerID_(firstPeerID)
    4953  {
     54    // Global initialization of ENet
    5055    enet_initialize();
     56
     57    // Register enet_deinitialize to be executed when the program exits normally
    5158    atexit(enet_deinitialize);
     59
     60    // Create mutexes for incoming and outgoing events
    5261    this->incomingEventsMutex_ = new boost::mutex;
    5362    this->outgoingEventsMutex_ = new boost::mutex;
    54 //     this->overallMutex_ = new boost::mutex;
    55   }
    56 
     63  }
     64
     65  /**
     66   * Destructor
     67   */
    5768  Connection::~Connection()
    5869  {
     70    // Delete the mutexes
    5971    delete this->incomingEventsMutex_;
    6072    delete this->outgoingEventsMutex_;
    61   }
    62 
     73
     74    // TODO: Why is enet_deinitialize() not called here?
     75    // Would make sense, since its counterpart, enet_initialize(), is called in the constructor.
     76  }
     77
     78  /**
     79   * Start the main communication thread.
     80   */
    6381  void Connection::startCommunicationThread()
    6482  {
     
    6785  }
    6886 
     87  /**
     88   * Stop the main communication thread.
     89   */
    6990  void Connection::stopCommunicationThread()
    7091  {
    7192    this->bCommunicationThreadRunning_ = false;
    72     if( !this->communicationThread_->timed_join(NETWORK_COMMUNICATION_THREAD_WAIT_TIME) )
    73     {
    74       // force thread to stop
     93    // Wait for peaceful termination
     94    if(!this->communicationThread_->timed_join(NETWORK_COMMUNICATION_THREAD_WAIT_TIME))
     95    {
     96      // Force thread to stop if the waiting time runs out.
    7597      this->communicationThread_->interrupt();
    7698    }
     
    78100  }
    79101
     102  /**
     103   * Send an outgoing event of type 'disconnectPeer'.
     104   * @param peerID The peer to which the event is sent
     105   */
    80106  void Connection::disconnectPeer(uint32_t peerID)
    81107  {
    82 //     this->overallMutex_->lock();
    83108    outgoingEvent outEvent = { peerID, OutgoingEventType::disconnectPeer, nullptr, 0 };
    84109   
     
    86111    this->outgoingEvents_.push_back(outEvent);
    87112    this->outgoingEventsMutex_->unlock();
    88 //     this->overallMutex_->unlock();
    89   }
    90  
     113  }
     114
     115  /**
     116   * Send an outgoing event of type 'disconnectPeers'.
     117   */
    91118  void Connection::disconnectPeers()
    92119  {
     
    98125  }
    99126
     127  /**
     128   * Send a packet.
     129   * @param packet Pointer to the packet to send
     130   * @param peerID The peer to which the event is sent
     131   * @param channelId The channel ID
     132   */
    100133  void Connection::addPacket(ENetPacket* packet, uint32_t peerID, uint8_t channelID)
    101134  {
    102 //     this->overallMutex_->lock();
    103135    outgoingEvent outEvent = { peerID, OutgoingEventType::sendPacket, packet, channelID };
    104136   
     
    106138    this->outgoingEvents_.push_back(outEvent);
    107139    this->outgoingEventsMutex_->unlock();
    108 //     this->overallMutex_->unlock();
    109   }
    110  
     140  }
     141 
     142  /**
     143   * Send a broadcast packet.
     144   * @param packet Pointer to the packet to send
     145   * @param channelId The channel ID
     146   */
    111147  void Connection::broadcastPacket(ENetPacket* packet, uint8_t channelID)
    112148  {
    113 //     this->overallMutex_->lock();
    114149    outgoingEvent outEvent = { 0, OutgoingEventType::broadcastPacket, packet, channelID };
    115150   
     
    117152    this->outgoingEvents_.push_back(outEvent);
    118153    this->outgoingEventsMutex_->unlock();
    119 //     this->overallMutex_->unlock();
    120   }
    121 
    122  
     154  }
     155
     156 
     157  /**
     158   * Main communication thread
     159   */
    123160  void Connection::communicationThread()
    124161  {
    125162    ENetEvent event;
    126163   
    127 //     this->overallMutex_->lock();
    128     while( bCommunicationThreadRunning_ )
     164    while(this->bCommunicationThreadRunning_)
    129165    {
    130166      // Receive all pending incoming Events (such as packets, connects and disconnects)
    131       while( enet_host_check_events( this->host_, &event ) > 0 )
     167      while(enet_host_check_events(this->host_, &event ) > 0)
    132168      {
    133         processIncomingEvent(event);
     169        this->processIncomingEvent(event);
    134170      }
    135171     
    136 //       this->overallMutex_->unlock();
     172      // Sleep for 1ms
     173      // TODO: Why?
    137174      msleep(1);
    138 //       this->overallMutex_->lock();
    139175     
    140176      // Send all waiting outgoing packets
     177      // TODO: Why do we need a mutex to read a single variable?
    141178      this->outgoingEventsMutex_->lock();
    142179      uint32_t outgoingEventsCount = this->outgoingEvents_.size();
    143180      this->outgoingEventsMutex_->unlock();
    144       while( outgoingEventsCount > 0 )
     181
     182      // TODO: Not convinced about how mutexes are used here, seems kinda pointless
     183      while(outgoingEventsCount > 0)
    145184      {
    146 //         orxout(verbose, context::network) << "outgoing event" << endl;
    147185        this->outgoingEventsMutex_->lock();
    148186        outgoingEvent outEvent = this->outgoingEvents_.front();
     
    150188        this->outgoingEventsMutex_->unlock();
    151189       
    152         processOutgoingEvent(outEvent);
     190        this->processOutgoingEvent(outEvent);
    153191       
    154192        this->outgoingEventsMutex_->lock();
     
    158196     
    159197      // Wait for incoming events (at most NETWORK_WAIT_TIMEOUT ms)
    160       if( enet_host_service( this->host_, &event, NETWORK_WAIT_TIMEOUT ) > 0 )
     198      if(enet_host_service(this->host_, &event, NETWORK_WAIT_TIMEOUT) > 0)
    161199      {
    162         processIncomingEvent(event);
     200        this->processIncomingEvent(event);
    163201      }
    164202    }
    165 //     this->overallMutex_->unlock();
    166   }
    167  
     203  }
     204 
     205  /**
     206   * Handle an incoming event.
     207   * @param event The incoming event
     208   */
    168209  void Connection::processIncomingEvent(ENetEvent& event)
    169210  {
    170211    incomingEvent inEvent;
    171212    // preprocess event
    172     switch( event.type )
     213    switch(event.type)
    173214    {
    174215      case ENET_EVENT_TYPE_CONNECT:
     
    192233  }
    193234 
     235  /**
     236   * Send an event.
     237   * @param event The event to send
     238   */
    194239  void Connection::processOutgoingEvent(outgoingEvent& event)
    195240  {
    196241    ENetPeer* peer;
    197     switch( event.type )
     242    switch(event.type)
    198243    {
    199244      case OutgoingEventType::sendPacket:
    200245        // check whether the peer is still/already in the peer list
    201         if( this->peerMap_.find(event.peerID) != this->peerMap_.end() )
     246        if(this->peerMap_.find(event.peerID) != this->peerMap_.end())
    202247        {
    203248          peer = this->peerMap_[event.peerID];
    204           enet_peer_send( peer, event.channelID, event.packet );
     249          enet_peer_send(peer, event.channelID, event.packet);
    205250        }
    206251        else
    207252        {
    208253          // peer probably already disconnected so just discard packet
    209           assert(event.peerID<this->nextPeerID_);
     254          assert(event.peerID < this->nextPeerID_);
    210255          enet_packet_destroy(event.packet);
    211256        }
    212257        break;
    213258      case OutgoingEventType::disconnectPeer:
    214         if( this->peerMap_.find(event.peerID) != this->peerMap_.end() )
     259        if(this->peerMap_.find(event.peerID) != this->peerMap_.end())
    215260        {
    216261          peer = this->peerMap_[event.peerID];
     
    220265        {
    221266          // peer probably already disconnected so just discard disconnect event
    222           assert(event.peerID<this->nextPeerID_);
     267          assert(event.peerID < this->nextPeerID_);
    223268        }
    224269        break;
    225270      case OutgoingEventType::disconnectPeers:
    226         disconnectPeersInternal();
     271        this->disconnectPeersInternal();
    227272        break;
    228273      case OutgoingEventType::broadcastPacket:
     
    234279  }
    235280
    236 
    237281  void Connection::disconnectPeersInternal()
    238282  {
     
    241285      enet_peer_disconnect(mapEntry.second, 0);
    242286    }
    243     uint32_t iterations = NETWORK_DISCONNECT_TIMEOUT/NETWORK_WAIT_TIMEOUT;
     287    uint32_t iterations = NETWORK_DISCONNECT_TIMEOUT / NETWORK_WAIT_TIMEOUT;
    244288    uint32_t i = 0;
    245289    while( this->peerMap_.size() && i++ < iterations )
  • code/branches/Masterserver_FS18/src/libraries/network/Connection.h

    r11071 r11829  
    9696
    9797  protected:
    98     Connection(uint32_t firstPeerID = NETWORK_PEER_ID_SERVER+1);
     98    Connection(uint32_t firstPeerID = NETWORK_PEER_ID_SERVER + 1);
    9999   
    100100    void startCommunicationThread();
     
    110110    void processQueue();
    111111    void waitOutgoingQueue();     // wait for the outgoing queue to become empty (everything processed by communication thread)
    112     virtual void addPeer(uint32_t peerID)=0;
    113     virtual void removePeer(uint32_t peerID)=0;
    114     virtual void processPacket( packet::Packet* packet)=0;
     112    virtual void addPeer(uint32_t peerID) = 0;
     113    virtual void removePeer(uint32_t peerID) = 0;
     114    virtual void processPacket( packet::Packet* packet) = 0;
    115115   
    116116    incomingEvent preprocessConnectEvent(ENetEvent& event);
     
    124124
    125125    ENetHost*                     host_;
     126
    126127  private:
    127128    void communicationThread();
     
    130131    bool                          bCommunicationThreadRunning_;
    131132    ENetAddress*                  bindAddress_;
     133
     134    // Queue for incoming events
    132135    std::deque<incomingEvent>     incomingEvents_;
     136
     137    // Queue for outgoing events
    133138    std::deque<outgoingEvent>     outgoingEvents_;
     139
    134140    boost::mutex*                 incomingEventsMutex_;
    135141    boost::mutex*                 outgoingEventsMutex_;
  • code/branches/Masterserver_FS18/src/libraries/network/GamestateManager.cc

    r11071 r11829  
    4343#include <cassert>
    4444#include <queue>
    45 // #include <boost/thread/mutex.hpp>
    4645
    4746#include "packet/Acknowledgement.h"
     
    5554#include "util/Clock.h"
    5655#include "util/OrxAssert.h"
    57 // #include "TrafficControl.h"
    5856
    5957namespace orxonox
     
    6260  currentGamestate_(nullptr), id_(0)
    6361  {
    64 //     trafficControl_ = new TrafficControl();
    65 //     threadMutex_ = new boost::mutex();
    66 //     threadPool_ = new ThreadPool();
    6762  }
    6863
    6964  GamestateManager::~GamestateManager()
    7065  {
    71     if( this->currentGamestate_ )
    72         delete this->currentGamestate_;
    73     for( const auto& mapEntry : gamestateQueue )
    74       delete mapEntry.second;
    75     for( const auto& mapEntryPeer : peerMap_ )
    76     {
    77       for( const auto& mapEntryGamestate : mapEntryPeer.second.gamestates )
    78         delete mapEntryGamestate.second;
    79     }
    80 //     this->trafficControl_->destroy();
    81 //     delete this->threadMutex_;
    82 //     delete this->threadPool_;
    83   }
    84 
    85   bool GamestateManager::update(){
    86 //     cleanup();
     66    if(this->currentGamestate_)
     67    {
     68      delete this->currentGamestate_;
     69    }
     70
     71    for(const auto& gsPair : this->gamestateQueue)
     72    {
     73      delete gsPair.second;
     74    }
     75
     76    for(const auto& peerPair : this->peerMap_)
     77    {
     78      for(const auto& gsPair : peerPair.second.gamestates)
     79      {
     80        delete gsPair.second;
     81      }
     82    }
     83  }
     84
     85  bool GamestateManager::update()
     86  {
    8787    return getSnapshot();
    8888  }
     
    9191  {
    9292    assert(gs);
    93     std::map<unsigned int, packet::Gamestate*>::iterator it = gamestateQueue.find(clientID);
    94     if(it!=gamestateQueue.end())
     93    // Search the queue for a gamestate for the client
     94    std::map<unsigned int, packet::Gamestate*>::iterator it = this->gamestateQueue.find(clientID);
     95    if(it != this->gamestateQueue.end())
    9596    {
    9697      // delete obsolete gamestate
    9798      delete it->second;
    9899    }
    99     gamestateQueue[clientID] = gs;
     100    // update the client's gamestate
     101    this->gamestateQueue[clientID] = gs;
     102
    100103    return true;
    101104  }
    102105
     106  /**
     107   * Process the queued gamestates.
     108   */
    103109  bool GamestateManager::processGamestates()
    104110  {
    105     if( this->gamestateQueue.empty() )
     111    // Queue is empty, nothing to do
     112    if(this->gamestateQueue.empty())
     113    {
    106114        return true;
     115    }
     116
    107117    // now push only the most recent gamestates we received (ignore obsolete ones)
    108     for(const auto& mapEntry : gamestateQueue)
    109     {
    110       OrxVerify(processGamestate(mapEntry.second), "ERROR: could not process Gamestate");
    111       sendAck( mapEntry.second->getID(), mapEntry.second->getPeerID() );
    112       delete mapEntry.second;
     118    for(const auto& gsPair : this->gamestateQueue)
     119    {
     120      OrxVerify(processGamestate(gsPair.second), "ERROR: could not process Gamestate");
     121      sendAck(gsPair.second->getID(), gsPair.second->getPeerID());
     122      delete gsPair.second;
    113123    }
    114124    // now clear the queue
    115     gamestateQueue.clear();
     125    this->gamestateQueue.clear();
     126
    116127    //and call all queued callbacks
    117128    NetworkCallbackManager::callCallbacks();
     129
    118130    return true;
    119131  }
    120132 
     133  /**
     134   * Send Acknowledgement packet.
     135   * @param gamestateId The gamestate ID we want to acknowledge
     136   * @param peerID The ID of the peer we want to send the Acknowledgement to
     137   */
    121138  bool GamestateManager::sendAck(unsigned int gamestateID, uint32_t peerID)
    122139  {
    123     assert( gamestateID != ACKID_NACK );
     140    assert(gamestateID != ACKID_NACK);
    124141    packet::Acknowledgement *ack = new packet::Acknowledgement(gamestateID, peerID);
    125     if( !this->sendPacket(ack))
     142    if(!this->sendPacket(ack))
    126143    {
    127144      orxout(internal_warning, context::network) << "could not ack gamestate: " << gamestateID << endl;
     
    135152  }
    136153
    137 
    138   bool GamestateManager::getSnapshot(){
    139     if ( currentGamestate_ != nullptr )
    140       delete currentGamestate_;
     154  /**
     155   * Update the current gamestate.
     156   */
     157  bool GamestateManager::getSnapshot()
     158  {
     159    // Delete current gamestate
     160    if (this->currentGamestate_ != nullptr)
     161    {
     162      delete this->currentGamestate_;
     163    }
     164
    141165    uint8_t gsMode;
    142     if( GameMode::isMaster() )
     166    if(GameMode::isMaster())
     167    {
    143168      gsMode = packet::GAMESTATE_MODE_SERVER;
    144     else
     169    }
     170    else
     171    {
    145172      gsMode = packet::GAMESTATE_MODE_CLIENT;
     173    }
     174
    146175    uint32_t newID;
    147     if( GameMode::isMaster() )
    148       newID = ++id_;
    149     else
    150     {
    151       assert(peerMap_.size()!=0);
    152       newID = peerMap_[NETWORK_PEER_ID_SERVER].lastReceivedGamestateID;
    153       if( newID == GAMESTATEID_INITIAL )
     176    if(GameMode::isMaster())
     177    {
     178      newID = ++this->id_;
     179    }
     180    else
     181    {
     182      assert(this->peerMap_.size() != 0);
     183      newID = this->peerMap_[NETWORK_PEER_ID_SERVER].lastReceivedGamestateID;
     184      if(newID == GAMESTATEID_INITIAL)
    154185      {
    155186        return false;
     
    157188    }
    158189   
    159     currentGamestate_ = new packet::Gamestate();
    160    
    161     if(!currentGamestate_->collectData(newID, gsMode))
    162     { //we have no data to send
    163       delete currentGamestate_;
    164       currentGamestate_=nullptr;
     190    // Create a new gamestate
     191    this->currentGamestate_ = new packet::Gamestate();
     192    if(!this->currentGamestate_->collectData(newID, gsMode))
     193    {
     194      // we have no data to send
     195      delete this->currentGamestate_;
     196      this->currentGamestate_ = nullptr;
    165197      return false;
    166198    }
     199
    167200    return true;
    168201  }
    169202
     203  /**
     204   * Return a vector with the gamestates of all peers.
     205   */
    170206  std::vector<packet::Gamestate*> GamestateManager::getGamestates()
    171207  {
    172     if(!currentGamestate_)
     208    // Current gamestate is empty
     209    if(!this->currentGamestate_){
    173210      return std::vector<packet::Gamestate*>();
     211    }
     212
    174213    std::vector<packet::Gamestate*> peerGamestates;
    175    
    176     for( const auto& mapEntry : peerMap_ )
    177     {
    178       if( !mapEntry.second.isSynched )
     214    // TODO: mapEntry is an incredibly bad name
     215    for(const auto& mapEntry : this->peerMap_)
     216    {
     217      if(!mapEntry.second.isSynched)
    179218      {
    180219        orxout(verbose_more, context::network) << "Server: not sending gamestate" << endl;
     
    198237      peerGamestates.push_back(nullptr);  // insert an empty gamestate* to be changed
    199238      finishGamestate( peerID, peerGamestates.back(), baseGamestate, currentGamestate_ );
    200       if( peerGamestates.back()==nullptr )
     239      if(peerGamestates.back() == nullptr)
     240      {
    201241        // nothing to send to remove pointer from vector
    202242        peerGamestates.pop_back();
    203       //FunctorMember<GamestateManager>* functor =
    204 //       ExecutorMember<GamestateManager>* executor = createExecutor( createFunctor(&GamestateManager::finishGamestate, this) );
    205 //       executor->setDefaultValues( cid, &clientGamestates.back(), client, currentGamestate_ );
    206 //       (*static_cast<Executor*>(executor))();
    207 //       this->threadPool_->passFunction( executor, true );
    208 //       (*functor)( cid, &(clientGamestates.back()), client, currentGamestate_ );
    209     }
    210 
    211 //     threadPool_->synchronise();
     243      }
     244    }
    212245
    213246    return peerGamestates;
     
    215248
    216249
    217   void GamestateManager::finishGamestate( unsigned int peerID, packet::Gamestate*& destgamestate, packet::Gamestate* base, packet::Gamestate* gamestate ) {
    218     //why are we searching the same client's gamestate id as we searched in
    219     //Server::sendGameState?
     250  void GamestateManager::finishGamestate(unsigned int peerID, packet::Gamestate*& destgamestate, packet::Gamestate* base, packet::Gamestate* gamestate)
     251  {
    220252    // save the (undiffed) gamestate in the clients gamestate map
    221     //chose wheather the next gamestate is the first or not
    222 
    223 //     packet::Gamestate *gs = gamestate->doSelection(clientID, 20000);
    224 //       packet::Gamestate* gs = new packet::Gamestate(*gamestate);
    225 //     packet::Gamestate* gs = gamestate;
     253    // choose whether the next gamestate is the first or not
     254
     255    // Create a copy of the gamestate
     256    // TODO: Does this actually create a copy of the gamestate?
    226257    packet::Gamestate *gs = new packet::Gamestate(*gamestate); //this is neccessary because the gamestate are being kept (to diff them later on) for each client seperately
    227 //     packet::Gamestate *gs = new packet::Gamestate();
    228 //     gs->collectData( id_, 0x1 );
    229 //     this->threadMutex_->lock();
    230     peerMap_[peerID].gamestates[gamestate->getID()]=gs;
    231 //     this->threadMutex_->unlock();
     258    this->peerMap_[peerID].gamestates[gamestate->getID()] = gs;
     259
     260    // Start the clock
    232261    Clock clock;
    233262    clock.capture();
     
    236265    {
    237266      packet::Gamestate *diffed1 = gs->diffVariables(base);
    238       if( diffed1->getDataSize() == 0 )
     267      if(diffed1->getDataSize() == 0)
    239268      {
    240269        delete diffed1;
     
    249278    }
    250279
    251 
    252 //     OrxVerify(gs->compressData(), "");
     280    // Stop the clock
    253281    clock.capture();
    254282    orxout(verbose_more, context::network) << "diff and compress time: " << clock.getDeltaTime() << endl;
    255 //     orxout(verbose_more, context::network) << "sending gamestate with id " << gs->getID();
    256 //     if(gamestate->isDiffed())
    257 //       orxout(verbose_more, context::network) << " and baseid " << gs->getBaseID() << endl;
    258 //     else
    259 //       orxout(verbose_more, context::network) << endl;
     283
     284
    260285    gs->setPeerID(peerID);
    261286    destgamestate = gs;
     
    263288
    264289
     290  /**
     291   * Acknowledge a received gamestate.
     292   * @param gamestateID The ID of the gamestate to be acknowledged
     293   * @param peerID The ID of the peer to send the Acknowledgement to
     294   */
    265295  bool GamestateManager::ackGamestate(unsigned int gamestateID, unsigned int peerID)
    266296  {
    267 //     ClientInformation *temp = ClientInformation::findClient(peerID);
    268 //     assert(temp);
     297    // Search for the peer in the peer map
    269298    std::map<uint32_t, peerInfo>::iterator it = this->peerMap_.find(peerID);
    270     assert(it!=this->peerMap_.end());
     299    assert(it != this->peerMap_.end());
     300
    271301    unsigned int curid = it->second.lastAckedGamestateID;
    272302
    273303    assert(gamestateID != ACKID_NACK);
    274 //     if(gamestateID == ACKID_NACK){
    275 //       it->second.lastAckedGamestateID = GAMESTATEID_INITIAL;
    276 // //       temp->setGamestateID(GAMESTATEID_INITIAL);
    277 //       // now delete all saved gamestates for this client
    278 //       std::map<uint32_t, packet::Gamestate*>::iterator it2;
    279 //       for(it2 = it->second.gamestates.begin(); it2!=it->second.gamestates.end(); ++it2 ){
    280 //         delete it2->second;
    281 //       }
    282 //       it->second.gamestates.clear();
    283 //       return true;
    284 //     }
    285 
    286 //    assert(curid==GAMESTATEID_INITIAL || curid<=gamestateID); // this line is commented out because acknowledgements are unreliable and may arrive in distorted order
    287     if( gamestateID <= curid && curid != GAMESTATEID_INITIAL )
     304
     305    // The gamestate has already been acknowledged, nothing to do
     306    if(gamestateID <= curid && curid != GAMESTATEID_INITIAL)
     307    {
    288308        return true;
    289 orxout(verbose, context::network) << "acking gamestate " << gamestateID << " for peerID: " << peerID << " curid: " << curid << endl;
     309    }
     310
     311    orxout(verbose, context::network) << "acking gamestate " << gamestateID << " for peerID: " << peerID << " curid: " << curid << endl;
    290312    std::map<uint32_t, packet::Gamestate*>::iterator it2;
    291     for( it2=it->second.gamestates.begin(); it2!=it->second.gamestates.end(); )
    292     {
    293       if( it2->second->getID() < gamestateID )
     313    for (it2 = it->second.gamestates.begin(); it2 != it->second.gamestates.end();)
     314    {
     315      if(it2->second->getID() < gamestateID)
    294316      {
    295317        delete it2->second;
     
    297319      }
    298320      else
     321      {
    299322        ++it2;
     323      }
    300324    }
    301325   
    302 //     std::map<unsigned int, packet::Gamestate*>::iterator it;
    303 //     for(it = gamestateMap_[peerID].begin(); it!=gamestateMap_[peerID].end() && it->first<gamestateID; ){
    304 //       delete it->second;
    305 //       gamestateMap_[peerID].erase(it++);
    306 //     }
     326    // update the last acked gamestate
    307327    it->second.lastAckedGamestateID = gamestateID;
    308 //     temp->setGamestateID(gamestateID);
    309 //     TrafficControl::processAck(peerID, gamestateID);
     328
    310329    return true;
    311330  }
    312331 
     332  /**
     333   * Return the ID of the last received gamestate for a certain peer
     334   * @param peerID The ID of the peer\
     335   */
    313336  uint32_t GamestateManager::getLastReceivedGamestateID(unsigned int peerID)
    314337  {
    315     assert( this->peerMap_.find(peerID)!=this->peerMap_.end() );
    316     if( this->peerMap_.find(peerID) != this->peerMap_.end() )
     338    if(this->peerMap_.find(peerID) != this->peerMap_.end())
     339    {
    317340      return this->peerMap_[peerID].lastReceivedGamestateID;
    318     else
     341    }
     342    else
     343    {
    319344      return GAMESTATEID_INITIAL;
     345    }
    320346  }
    321347 
    322  
     348  /**
     349   * Add a peer to the game.
     350   * @param peerID The ID of the peer to add.
     351   */
    323352  void GamestateManager::addPeer(uint32_t peerID)
    324353  {
    325     assert(peerMap_.find(peerID)==peerMap_.end());
    326     peerMap_[peerID].peerID = peerID;
    327     peerMap_[peerID].lastReceivedGamestateID = GAMESTATEID_INITIAL;
    328     peerMap_[peerID].lastAckedGamestateID = GAMESTATEID_INITIAL;
    329     if( GameMode::isMaster() )
    330       peerMap_[peerID].isSynched = false;
    331     else
    332       peerMap_[peerID].isSynched = true;
    333   }
    334 
     354    // Ensure that the peer doesn't already exist.
     355    assert(this->peerMap_.find(peerID) == this->peerMap_.end());
     356
     357    // Create the peerInfo struct for the peer
     358    this->peerMap_[peerID].peerID = peerID;
     359    this->peerMap_[peerID].lastReceivedGamestateID = GAMESTATEID_INITIAL;
     360    this->peerMap_[peerID].lastAckedGamestateID = GAMESTATEID_INITIAL;
     361    if(GameMode::isMaster())
     362    {
     363      this->peerMap_[peerID].isSynched = false;
     364    }
     365    else
     366    {
     367      this->peerMap_[peerID].isSynched = true;
     368    }
     369  }
     370
     371  /**
     372   * Remove a peer from the game.
     373   * @param peerID The ID of the peer to be removed
     374   */
    335375  void GamestateManager::removePeer(uint32_t peerID)
    336376  {
    337     assert(peerMap_.find(peerID)!=peerMap_.end());
    338     for( const auto& mapEntry : peerMap_[peerID].gamestates )
     377    // Make sure that the peer exists
     378    assert(this->peerMap_.find(peerID) != this->peerMap_.end());
     379
     380    for (const auto& mapEntry : this->peerMap_[peerID].gamestates)
    339381    {
    340382      delete mapEntry.second;
    341383    }
    342     peerMap_.erase(peerMap_.find(peerID));
    343   }
    344 
    345 
    346 //   void GamestateManager::removeClient(ClientInformation* client){
    347 //     assert(client);
    348 //     std::map<unsigned int, std::map<unsigned int, packet::Gamestate*>>::iterator clientMap = gamestateMap_.find(client->getID());
    349 //     // first delete all remained gamestates
    350 //     std::map<unsigned int, packet::Gamestate*>::iterator it;
    351 //     for(it=clientMap->second.begin(); it!=clientMap->second.end(); it++)
    352 //       delete it->second;
    353 //     // now delete the clients gamestatemap
    354 //     gamestateMap_.erase(clientMap);
    355 //   }
    356 
     384    this->peerMap_.erase(this->peerMap_.find(peerID));
     385  }
     386
     387  /**
     388   * Process an incoming Gamestate packet.
     389   * @param gs Pointer to the incoming Gamestate packet
     390   */
    357391  bool GamestateManager::processGamestate(packet::Gamestate *gs)
    358392  {
     393    // Decompress if necessary
    359394    if(gs->isCompressed())
    360395    {
     
    362397    }
    363398    assert(!gs->isDiffed());
     399
    364400    uint8_t gsMode;
    365     if( GameMode::isMaster() )
     401    if(GameMode::isMaster())
     402    {
    366403      gsMode = packet::GAMESTATE_MODE_SERVER;
    367     else
     404    }
     405    else
     406    {
    368407      gsMode = packet::GAMESTATE_MODE_CLIENT;
    369     if( gs->spreadData(gsMode) )
     408    }
     409
     410    if(gs->spreadData(gsMode))
    370411    {
    371412      this->peerMap_[gs->getPeerID()].lastReceivedGamestateID = gs->getID();
     
    373414    }
    374415    else
     416    {
    375417      return false;
     418    }
    376419  }
    377420
  • code/branches/Masterserver_FS18/src/libraries/network/GamestateManager.h

    r11071 r11829  
    6262  * b: new Gamestate
    6363  * x: diffed and compressed gamestate
    64   * x=(a^b)
    65   * b=(a^x)
    66   * diff(a,diff(a,x))=x (hope this is correct)
     64  * x = (a ^ b)
     65  * b = (a ^ x)
     66  * diff(a, diff(a, x)) = x (hope this is correct)
    6767  * @author Oliver Scheuss
    6868  */
     
    7575      uint32_t  lastAckedGamestateID;     //!< id of the last gamestate on which we received an ack from the peer
    7676      bool      isSynched;
    77       std::map< uint32_t, packet::Gamestate* > gamestates;
     77      std::map<uint32_t, packet::Gamestate*> gamestates;
    7878    };
    7979
     
    8686    virtual bool      ackGamestate(unsigned int gamestateID, unsigned int peerID) override;
    8787    virtual uint32_t  getLastReceivedGamestateID( unsigned int peerID ) override;
    88     virtual uint32_t  getCurrentGamestateID() override{ if( currentGamestate_) return currentGamestate_->getID(); else return GAMESTATEID_INITIAL; }
     88    virtual uint32_t  getCurrentGamestateID() override { if(currentGamestate) return currentGamestate_->getID(); else return GAMESTATEID_INITIAL; }
    8989
    9090    bool processGamestates();
     
    9898    void addPeer( uint32_t peerID );
    9999    void setSynched( uint32_t peerID )
    100       { assert(peerMap_.find(peerID)!=peerMap_.end()); peerMap_[peerID].isSynched = true; }
     100      { assert(peerMap_.find(peerID) != peerMap_.end()); peerMap_[peerID].isSynched = true; }
    101101    void removePeer( uint32_t peerID );
    102     bool hasPeers(){ return this->peerMap_.size()!=0; }
    103 //     void removeClient(ClientInformation *client);
     102    bool hasPeers(){ return this->peerMap_.size() != 0; }
     103
    104104  protected:
    105105    virtual bool sendPacket( packet::Packet* packet ) = 0;
     106
    106107  private:
    107108    bool processGamestate(packet::Gamestate *gs);
    108109
    109 //     std::map<unsigned int, std::map<unsigned int, packet::Gamestate*>> gamestateMap_;
     110    // TODO: What is the purpose of the gamestateQueue?
    110111    std::map<unsigned int, packet::Gamestate*> gamestateQueue;
    111 //     std::map<unsigned int, uint32_t> lastProcessedGamestateID_;
     112
     113    // Each peerID maps to a peerInfo struct
    112114    std::map<uint32_t, peerInfo> peerMap_;
     115
     116    // always contains the latest gamestate
    113117    packet::Gamestate* currentGamestate_;
    114 //     TrafficControl *trafficControl_;
    115118    unsigned int id_;
    116 //     boost::mutex* threadMutex_;
    117     ThreadPool*   /*thread*/Pool_;
     119    ThreadPool* Pool_;
    118120  };
    119121
  • code/branches/Masterserver_FS18/src/libraries/network/Host.cc

    r11071 r11829  
    4444  SetConsoleCommand(__CC_printRTT_group, __CC_printRTT_name, &Host::printRTT);
    4545
    46   // Host*               Host::instance_=nullptr;
    47   uint32_t            Host::clientID_s=0;
    48 //   uint32_t            Host::shipID_s=-1;
     46  uint32_t            Host::clientID_s = 0;
    4947  std::vector<Host*>  Host::instances_s;
    5048
     
    5452  Host::Host()
    5553  {
    56   //   assert(instance_==nullptr);
    57     instances_s.push_back(this);
     54    Host::instances_s.push_back(this);
     55
     56    // TODO: What does this do?
    5857    ModifyConsoleCommand(__CC_printRTT_group, __CC_printRTT_name).setObject(this);
     58
    5959    this->bIsActive_ = false;
    6060  }
     
    6666  Host::~Host()
    6767  {
    68     assert( std::find( instances_s.begin(), instances_s.end(), this )!=instances_s.end() );
    69     instances_s.erase(std::find( instances_s.begin(), instances_s.end(), this ));
     68    assert(std::find( instances_s.begin(), instances_s.end(), this ) != instances_s.end());
     69    Host::instances_s.erase(std::find( instances_s.begin(), instances_s.end(), this ));
    7070    ModifyConsoleCommand(__CC_printRTT_group, __CC_printRTT_name).setObject(nullptr);
    7171  }
     
    8080  void Host::addPacket(ENetPacket *packet, int clientID, uint8_t channelID)
    8181  {
    82     for(Host* host : instances_s)
     82    for (Host* host : instances_s)
    8383    {
    84       if( host->isActive() )
     84      if (host->isActive())
    8585      {
    8686        host->queuePacket(packet, clientID, channelID);
     
    9797  void Host::sendChat(const std::string& message, unsigned int sourceID, unsigned int targetID)
    9898  {
    99     for(Host* host : instances_s)
    100       if( host->isActive() )
     99    for (Host* host : instances_s)
     100    {
     101      if (host->isActive())
     102      {
    101103        host->doSendChat(message, sourceID, targetID);
     104      }
     105    }
    102106  }
    103107
     
    108112  {
    109113    for (NetworkChatListener* listener : ObjectList<NetworkChatListener>())
     114    {
    110115      listener->incomingChat(message, sourceID);
     116    }
    111117  }
    112118
     
    114120  bool Host::isServer()
    115121  {
    116     for (Host* host : instances_s)
     122    for (Host* host : Host::instances_s)
    117123    {
    118       if( host->isActive() )
     124      if (host->isActive())
    119125      {
    120         if( host->isServer_() )
     126        if (host->isServer_())
     127        {
    121128          return true;
     129        }
    122130      }
    123131    }
     
    125133  }
    126134
     135  /**
     136   * Singleton implementation. Return the first active instance.
     137   */
    127138  Host* Host::getActiveInstance()
    128139  {
    129140    std::vector<Host*>::iterator it = Host::instances_s.begin();
    130     while( it != Host::instances_s.end() )
     141    while (it != Host::instances_s.end())
    131142    {
    132       if( (*it)->isActive() )
     143      if ((*it)->isActive())
     144      {
    133145        return *it;
     146      }
    134147      else
     148      {
    135149        ++it;
     150      }
    136151    }
    137152    return nullptr;
  • code/branches/Masterserver_FS18/src/libraries/network/Host.h

    r8858 r11829  
    4040  const unsigned int CLIENTID_SERVER = 0;
    4141  const unsigned int NETWORK_FREQUENCY = 25;
    42   const float NETWORK_PERIOD = 1.0f/NETWORK_FREQUENCY;
     42  const float NETWORK_PERIOD = 1.0f / NETWORK_FREQUENCY;
    4343
    4444/**
     
    5555
    5656  private:
    57     virtual void queuePacket(ENetPacket *packet, int clientID, uint8_t channelID)=0;
     57    virtual void queuePacket(ENetPacket *packet, int clientID, uint8_t channelID) = 0;
    5858    virtual bool isServer_()=0;
    5959
     
    6363    void setActive( bool bActive ){ bIsActive_ = bActive; }
    6464
    65     virtual void doSendChat(const std::string& message, unsigned int sourceID, unsigned int targetID)=0;
    66     virtual void doReceiveChat(const std::string& message, unsigned int sourceID, unsigned int targetID)=0;
     65    virtual void doSendChat(const std::string& message, unsigned int sourceID, unsigned int targetID) = 0;
     66    virtual void doReceiveChat(const std::string& message, unsigned int sourceID, unsigned int targetID) = 0;
    6767
    6868  public:
     
    7474    static bool isServer();
    7575    static void sendChat(const std::string& message, unsigned int sourceID, unsigned int targetID);
    76     virtual void printRTT()=0;
     76    virtual void printRTT() = 0;
    7777    bool isActive(){ return bIsActive_; }
     78   
    7879  private:
    7980    static uint32_t clientID_s;
  • code/branches/Masterserver_FS18/src/libraries/network/Server.cc

    r11103 r11829  
    5555#include "packet/Gamestate.h"
    5656#include "packet/Welcome.h"
    57 // #include "ClientInformation.h"
    5857#include "FunctionCallManager.h"
    5958#include "GamestateManager.h"
     
    6968  Server::Server()
    7069  {
    71     this->timeSinceLastUpdate_=0;
    72   }
    73 
     70    this->timeSinceLastUpdate_ = 0;
     71  }
     72
     73  /**
     74  * Constructor
     75  * @param port Port to listen on
     76  */
    7477  Server::Server(int port)
    7578  {
    76     this->setPort( port );
    77     this->timeSinceLastUpdate_=0;
    78   }
    79 /*
    80   Server::Server(int port, const std::string name)
    81   {
    82     this->setPort( port );
    83     this->timeSinceLastUpdate_=0;
    84     this->serverName_=name;
    85   }*/
     79    this->setPort(port);
     80    this->timeSinceLastUpdate_ = 0;
     81  }
     82
    8683  /**
    8784  * Constructor
     
    9188  Server::Server(int port, const std::string& bindAddress)
    9289  {
    93     this->setPort( port );
    94     this->setBindAddress( bindAddress );
    95     this->timeSinceLastUpdate_=0;
     90    this->setPort(port);
     91    this->setBindAddress(bindAddress);
     92    this->timeSinceLastUpdate_ = 0;
    9693  }
    9794
     
    156153    LANDiscoverable::update();
    157154
    158     if ( GamestateManager::hasPeers() )
     155    if (GamestateManager::hasPeers())
    159156    {
    160157      // process incoming gamestates
     
    163160
    164161      // send function calls to clients
    165       FunctionCallManager::sendCalls( static_cast<Host*>(this) );
    166 
    167       //this steers our network frequency
    168       timeSinceLastUpdate_+=time.getDeltaTime();
    169       if(timeSinceLastUpdate_>=NETWORK_PERIOD)
     162      FunctionCallManager::sendCalls(static_cast<Host*>(this));
     163
     164      // this steers our network frequency
     165      timeSinceLastUpdate_ += time.getDeltaTime();
     166      if(timeSinceLastUpdate_ >= NETWORK_PERIOD)
    170167      {
    171         timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
     168        timeSinceLastUpdate_ -= static_cast<unsigned int>(timeSinceLastUpdate_ / NETWORK_PERIOD) * NETWORK_PERIOD;
    172169        updateGamestate();
    173170      }
    174 //       sendPackets(); // flush the enet queue
    175171    }
    176172  }
     
    182178
    183179  /**
    184    * @brief: returns ping time to client in milliseconds
     180   * Return ping time to client in milliseconds.
    185181   */
    186182  unsigned int Server::getRTT(unsigned int clientID)
    187183  {
    188 //     assert(ClientInformation::findClient(clientID));
    189 //     return ClientInformation::findClient(clientID)->getRTT();
    190     // TODO: reimplement
     184    // TODO: Implement
    191185    return 0;
    192186  }
    193187
     188  /**
     189   * Print ping time to client in milliseconds.
     190   */
    194191  void Server::printRTT()
    195192  {
    196 //     for( ClientInformation* temp=ClientInformation::getBegin(); temp!=nullptr; temp=temp->next() )
    197 //       orxout(message) << "Round trip time to client with ID: " << temp->getID() << " is " << temp->getRTT() << " ms" << endl;
    198   }
    199 
    200   /**
    201    * @brief: return packet loss ratio to client (scales from 0 to 1)
     193    // TODO: Implement
     194  }
     195
     196  /**
     197   * Return packet loss ratio to client (scales from 0 to 1).
    202198   */
    203199  float Server::getPacketLoss(unsigned int clientID)
    204200  {
    205 //     assert(ClientInformation::findClient(clientID));
    206 //     return ClientInformation::findClient(clientID)->getPacketLoss();
     201    // TODO: Implement
    207202    return 0.;
    208203  }
    209204
    210205  /**
    211   * takes a new snapshot of the gamestate and sends it to the clients
    212   */
     206   * Take a new snapshot of the gamestate and send it to the clients.
     207   */
    213208  void Server::updateGamestate()
    214209  {
    215     if( this->clientIDs_.size()==0 )
    216       //no client connected
     210    if(this->clientIDs_.size() == 0)
     211    {
     212      // no client connected
    217213      return;
     214    }
    218215    GamestateManager::update();
    219 //     orxout(verbose_more, context::network) << "Server: one gamestate update complete, goig to sendGameState" << endl;
    220     //orxout(verbose_more, context::network) << "updated gamestate, sending it" << endl;
    221     //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
    222216    sendGameStates();
    223217    sendObjectDeletes();
    224 //     orxout(verbose_more, context::network) << "Server: one sendGameState turn complete, repeat in next tick" << endl;
    225     //orxout(verbose_more, context::network) << "sent gamestate" << endl;
    226   }
    227 
    228   /**
    229   * sends the current gamestate to all peers
    230   */
     218  }
     219
     220  /**
     221   * Send the current gamestate to all peers.
     222   */
    231223  bool Server::sendGameStates()
    232224  {
    233225    std::vector<packet::Gamestate*> gamestates = GamestateManager::getGamestates();
    234     for( packet::Gamestate* gamestate : gamestates )
     226    for(packet::Gamestate* gamestate : gamestates)
    235227    {
    236228      gamestate->send(static_cast<Host*>(this));
     
    240232
    241233
     234  /**
     235   * Send 'DeleteObjects' packet
     236   */
    242237  bool Server::sendObjectDeletes()
    243238  {
    244 //     ClientInformation *temp = ClientInformation::getBegin();
    245 //     if( temp == nullptr )
    246       //no client connected
    247     if( this->clientIDs_.size()==0 )
     239    // no client connected
     240    if(this->clientIDs_.size() == 0)
     241    {
    248242      return true;
     243    }
     244
    249245    packet::DeleteObjects *del = new packet::DeleteObjects();
    250246    if(!del->fetchIDs())
     
    253249      return true;  //everything ok (no deletes this tick)
    254250    }
    255 //     orxout(verbose, context::network) << "sending DeleteObjects" << endl;
    256 //     while(temp != nullptr){
    257 //       if( !(temp->getSynched()) )
    258 //       {
    259 //         orxout(verbose_more, context::network) << "Server: not sending gamestate" << endl;
    260 //         temp=temp->next();
    261 //         continue;
    262 //       }
    263 //       int cid = temp->getID(); //get client id
    264 //       packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
    265 //       assert(cd);
     251
    266252    del->setPeerID(NETWORK_PEER_ID_BROADCAST);
    267     if ( !del->send( static_cast<Host*>(this) ) )
     253    if (!del->send( static_cast<Host*>(this)))
     254    {
    268255      orxout(internal_warning, context::network) << "Server: could not broadcast deleteObjects packet" << endl;
    269 //       temp=temp->next();
    270       // gs gets automatically deleted by enet callback
    271 //     }
    272 //     delete del;
     256    }
     257
     258    // TODO: Possible memory leak?
     259    // del is allocated but only deleted if fetchIDs() returns false
     260
    273261    return true;
    274262  }
    275263
    276 
     264  /**
     265   * Add a new peer to the server.
     266   */
    277267  void Server::addPeer(uint32_t peerID)
    278268  {
    279 //     static unsigned int newid=1;
    280 //
    281 //     orxout(internal_info, context::network) << "Server: adding client" << endl;
    282 //     ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
    283 //     if(!temp)
    284 //     {
    285 //       orxout(internal_warning, context::network) << "Server: could not add client" << endl;
    286 //     }
    287 //     temp->setID(newid);
    288 //     temp->setPeer(event->peer);
    289 
    290269    // inform all the listeners
    291270    this->clientIDs_.push_back(peerID);
     
    296275    GamestateManager::addPeer(peerID);
    297276
    298 //     ++newid;
    299 
    300277    orxout(internal_info, context::network) << "Server: added client id: " << peerID << endl;
    301278
    302279    createClient(peerID);
    303 }
    304 
     280  }
     281
     282  /**
     283   * Remove a peer from the server.
     284   */
    305285  void Server::removePeer(uint32_t peerID)
    306286  {
    307287    orxout(verbose, context::network) << "removing client from list" << endl;
    308 //     ClientInformation *client = ClientInformation::findClient(&event->peer->address);
    309 //     if(!client)
    310 //       return;
    311 //     else
    312 //     {
    313   std::vector<uint32_t>::iterator it;
    314   for( it=this->clientIDs_.begin(); it!=this->clientIDs_.end(); ++it )
    315   {
    316     if( *it == peerID )
    317     {
    318       this->clientIDs_.erase(it);
    319       break;
    320     }
    321   }
    322   WANDiscoverable::updateClientNumber(this->clientIDs_.size());
    323   LANDiscoverable::updateClientNumber(this->clientIDs_.size());
    324 
    325   ClientConnectionListener::broadcastClientDisconnected(peerID);
    326   GamestateManager::removePeer(peerID);
    327       //ServerConnection::disconnectClient( client );
    328       //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now
    329 //       delete client;
    330 //     }
    331   }
    332 
     288
     289    // erase the peer from the list
     290    std::vector<uint32_t>::iterator it;
     291    for(it=this->clientIDs_.begin(); it!=this->clientIDs_.end(); ++it)
     292    {
     293      if(*it == peerID)
     294      {
     295        this->clientIDs_.erase(it);
     296        break;
     297      }
     298    }
     299
     300    // TODO: What happens if no peer with this ID is found?
     301    // Should probably at least log
     302
     303    WANDiscoverable::updateClientNumber(this->clientIDs_.size());
     304    LANDiscoverable::updateClientNumber(this->clientIDs_.size());
     305
     306    // Send 'clientDisconnected' message
     307    ClientConnectionListener::broadcastClientDisconnected(peerID);
     308
     309    GamestateManager::removePeer(peerID);
     310  }
     311
     312  /**
     313   * Process an incoming packet.
     314   */
    333315  void Server::processPacket(packet::Packet* packet)
    334316  {
    335     if( packet->isReliable() )
    336     {
    337       if( this->getLastReceivedGamestateID(packet->getPeerID()) >= packet->getRequiredGamestateID() )
     317    if(packet->isReliable())
     318    {
     319      if(this->getLastReceivedGamestateID(packet->getPeerID()) >= packet->getRequiredGamestateID())
     320      {
    338321        packet->process(static_cast<Host*>(this));
     322      }
    339323      else
     324      {
    340325        this->packetQueue_.push_back(packet);
     326      }
    341327    }
    342328    else
     329    {
    343330      packet->process(static_cast<Host*>(this));
    344   }
    345 
    346 
     331    }
     332  }
     333
     334  /**
     335   * Create a client.
     336   */
    347337  bool Server::createClient(int clientID)
    348338  {
    349 //     ClientInformation *temp = ClientInformation::findClient(clientID);
    350 //     if(!temp)
    351 //     {
    352 //       orxout(internal_error, context::network) << "Server. could not create client with id: " << clientID << endl;
    353 //       return false;
    354 //     }
    355 //     orxout(verbose, context::network) << "Con.Man: creating client id: " << temp->getID() << endl;
    356339
    357340    // synchronise class ids
     
    361344    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
    362345    fIDs->setPeerID(clientID);
    363     bool b = fIDs->send( static_cast<Host*>(this) );
     346    bool b = fIDs->send(static_cast<Host*>(this));
    364347    assert(b);
    365 
    366 //     temp->setSynched(true);
     348    // TODO: assert probably isn't the way to go here, as a packet which fails to send will crash the game...
     349
    367350    GamestateManager::setSynched(clientID);
    368351
     352    // Send 'Welcome' packet to client
    369353    orxout(verbose, context::network) << "sending welcome" << endl;
    370354    packet::Welcome *w = new packet::Welcome(clientID);
    371355    w->setPeerID(clientID);
    372     b = w->send( static_cast<Host*>(this) );
     356    b = w->send(static_cast<Host*>(this));
    373357    assert(b);
     358    // TODO: assert probably isn't the way to go here, as a packet which fails to send will crash the game...
     359
    374360    (void)b; // avoid compiler warning
    375 //     packet::Gamestate *g = new packet::Gamestate();
    376 //     g->setPeerID(clientID);
    377 //     b = g->collectData(0,packet::GAMESTATE_MODE_SERVER);
    378 //     assert(b);
    379 //     if(!b)
    380 //       return false; //no data for the client
    381 // //     b = g->compressData();
    382 // //     assert(b);
    383 //     b = g->send( static_cast<Host*>(this) );
    384 //     assert(b);
    385361    return true;
    386362  }
    387363
    388   void Server::disconnectClient( uint32_t clientID )
    389   {
    390     ServerConnection::disconnectClient( clientID );
    391     GamestateManager::removePeer( clientID );
    392     // inform all the listeners
    393     // ClientConnectionListener::broadcastClientDisconnected(client->getID()); // this is done in ClientInformation now
     364  /**
     365   * Disconnect a client.
     366   */
     367  void Server::disconnectClient(uint32_t clientID)
     368  {
     369    ServerConnection::disconnectClient(clientID);
     370    GamestateManager::removePeer(clientID);
    394371  }
    395372
     
    404381    // check if the target exists. just ignore the message otherwise
    405382    if (!this->isValidTarget(targetID)) // TODO: remove this if an invalid clientIDs don't trigger assertions anymore
     383    {
    406384      return;
     385    }
    407386
    408387    // send the message to the target
    409388    packet::Chat* packet = new packet::Chat(message, sourceID, targetID);
    410389    packet->setPeerID(targetID);
    411     packet->send( static_cast<Host*>(this) );
     390    packet->send(static_cast<Host*>(this));
    412391
    413392    // if the target is (or includes) this host as well, call the parent function which passes the message to the listeners
    414393    if (targetID == NETWORK_PEER_ID_BROADCAST || targetID == Host::getPlayerID())
     394    {
    415395      Host::doReceiveChat(message, sourceID, targetID);
     396    }
    416397  }
    417398
     
    431412  bool Server::isValidTarget(unsigned int targetID)
    432413  {
     414    // Broadcast or server ID are okay
    433415    if (targetID == NETWORK_PEER_ID_BROADCAST || targetID == NETWORK_PEER_ID_SERVER)
     416    {
    434417      return true;
    435 
    436     for( uint32_t id : this->clientIDs_ )
    437       if( id == targetID )
     418    }
     419
     420    // IDs in the client list are okay also
     421    for(uint32_t id : this->clientIDs_)
     422    {
     423      if(id == targetID)
     424      {
    438425        return true;
     426      }
     427    }
    439428
    440429    return false;
     
    443432  void Server::syncClassid(unsigned int clientID)
    444433  {
    445     int failures=0;
    446434    packet::ClassID *classid = new packet::ClassID();
    447435    classid->setPeerID(clientID);
    448     while(!classid->send( static_cast<Host*>(this) ) && failures < 10){
     436    // TODO: Better to do this with a for loop
     437    int failures = 0;
     438    while(!classid->send(static_cast<Host*>(this)) && failures < 10)\
     439    {
    449440      failures++;
    450441    }
    451442    assert(failures<10);
     443    // TODO: assert probably isn't the way to go here, as 10 failed packets will crash the game...
    452444    orxout(verbose, context::network) << "syncClassid:\tall synchClassID packets have been sent" << endl;
    453445  }
  • code/branches/Masterserver_FS18/src/libraries/network/ServerConnection.cc

    r11071 r11829  
    3636#include "util/Output.h"
    3737#include <util/Sleep.h>
    38 // #include "ClientInformation.h"
    3938
    4039namespace orxonox
    4140{
    4241
     42  // TODO: Calls to the Connection superclass are done as follows:
     43  // Connection::startCommunicationThread()
     44  // However, these methods are not overridden.
     45  // Why can't we just do this->startCommunicationThread()?
     46
     47  /**
     48   * Constructor
     49   */
    4350  ServerConnection::ServerConnection():
    4451    bListening_(false)
    4552  {
    4653    this->bindAddress_ = new ENetAddress();
    47 //     memset(this->bindAddress_, 0, sizeof(ENetAddress));
    4854    this->bindAddress_->host = ENET_HOST_ANY;
    4955    this->bindAddress_->port = NETWORK_PORT;
     
    5157  }
    5258
     59  /**
     60   * Destructor
     61   */
    5362  ServerConnection::~ServerConnection()
    5463  {
    55     if ( this->bListening_ )
    56       closeListener();
     64    if (this->bListening_)
     65    {
     66      this->closeListener();
     67    }
    5768    delete this->bindAddress_;
    5869  }
    5970
    60   void ServerConnection::setBindAddress( const std::string& bindAddress )
     71  /**
     72   * Set address on which to listen.
     73   * @param bindAddress The address on which to listen
     74   */
     75  void ServerConnection::setBindAddress(const std::string& bindAddress)
    6176  {
    62     if (enet_address_set_host (this->bindAddress_, bindAddress.c_str()) < 0)
    63         orxout(internal_error, context::network) << "Could not resolve \"" << bindAddress << "\"." << endl;
     77    if (enet_address_set_host(this->bindAddress_, bindAddress.c_str()) < 0)
     78    {
     79      orxout(internal_error, context::network) << "Could not resolve \"" << bindAddress << "\"." << endl;
     80    }
    6481  }
    6582
    66   void ServerConnection::setPort( unsigned int port ) {
     83  /**
     84   * Set port on which to listen on.
     85   * @param port The port on which to listen on.
     86   */
     87  void ServerConnection::setPort(unsigned int port) {
    6788      this->bindAddress_->port = port;
    6889  }
     
    7394    this->host_ = enet_host_create(this->bindAddress_, NETWORK_MAX_CONNECTIONS, NETWORK_CHANNEL_COUNT, 0, 0);
    7495   
    75     if ( this->host_ == nullptr )
     96    if (this->host_ == nullptr)
    7697    {
    7798        orxout(internal_error, context::network) << "ServerConnection: host_ == nullptr" << endl;
     
    81102    // enable compression
    82103    this->enableCompression();
     104
     105    // ensure that either IPv4 or IPv6 succeeded
    83106    assert( this->host_->socket4 != ENET_SOCKET_NULL || this->host_->socket6 != ENET_SOCKET_NULL );
     107
    84108    if (this->host_->socket4 == ENET_SOCKET_NULL)
     109    {
    85110        orxout(internal_warning, context::network) << "IPv4 Socket failed." << endl;
     111    }
    86112    else if (this->host_->socket6 == ENET_SOCKET_NULL)
     113    {
    87114        orxout(internal_warning, context::network) << "IPv6 Socket failed." << endl;
     115    }
    88116    else
     117    {
    89118        orxout(internal_info, context::network) << "Using IPv4 and IPv6 Sockets." << endl;
     119    }
    90120   
    91121    // start communication thread
     
    95125  }
    96126
     127  /**
     128   * Stop listening.
     129   */
    97130  bool ServerConnection::closeListener()
    98131  {
    99     this->bListening_=false;
     132    this->bListening_ = false;
    100133    disconnectClients();
    101134    Connection::stopCommunicationThread();
     
    104137  }
    105138
     139  /**
     140   * Add outgoing packet to queue.
     141   * @param packet The packet to send
     142   * @param clientID The ID of the recipient
     143   * @param channelID The channel ID
     144   * TODO: Not sure yet how this actually works
     145   */
    106146  void ServerConnection::addPacket(ENetPacket *packet, unsigned int clientID, uint8_t channelID)
    107147  {
    108     if ( clientID == NETWORK_PEER_ID_BROADCAST )
     148    if (clientID == NETWORK_PEER_ID_BROADCAST)
    109149    {
    110150      broadcastPacket(packet, channelID);
     
    112152    else
    113153    {
    114 //       ClientInformation *temp = ClientInformation::findClient(clientID);
    115 //       if(!temp){
    116 //         orxout(internal_warning, context::network) << "C.Man: addPacket findClient failed" << endl;
    117 //       }
    118154      Connection::addPacket(packet, clientID, channelID);
    119155    }
    120156  }
    121157
    122 //   void ServerConnection::disconnectClient(ClientInformation *client)
    123 //   {
    124 //     Connection::disconnectPeer( client->getPeer() );
    125 //   }
    126 
     158  /**
     159   * Terminate connection with a peer.
     160   * @param clientID The peer with which to terminate the connection.
     161   */
    127162  void ServerConnection::disconnectClient(int clientID)
    128163  {
    129 //     ClientInformation *client = ClientInformation::findClient(clientID);
    130 //     if(client)
    131164    Connection::disconnectPeer(clientID);
    132165  }
    133166
     167  /**
     168   * Disconnect all peers.
     169   */
    134170  void ServerConnection::disconnectClients()
    135171  {
     
    138174    return;
    139175  }
    140 
    141 
    142 //   int ServerConnection::getClientID(ENetPeer* peer)
    143 //   {
    144 //     return getClientID(&(peer->address));
    145 //   }
    146 
    147 //   int ServerConnection::getClientID(ENetAddress* address)
    148 //   {
    149 //     return ClientInformation::findClient(address)->getID();
    150 //   }
    151 //
    152 //   ENetPeer *ServerConnection::getClientPeer(int clientID)
    153 //   {
    154 //     return ClientInformation::findClient(clientID)->getPeer();
    155 //   }
    156 
    157 
    158176}
  • code/branches/Masterserver_FS18/src/libraries/network/ServerConnection.h

    r8327 r11829  
    4747{
    4848
    49   class _NetworkExport ServerConnection : public Connection{
     49  class _NetworkExport ServerConnection : public Connection
     50  {
    5051  public:
    5152    ~ServerConnection();
     
    5758    bool closeListener();
    5859    void addPacket(ENetPacket *packet, unsigned int ID, uint8_t channelID);
    59 //     virtual void disconnectClient(ClientInformation *client);
    6060    void disconnectClient(int clientID);
     61
    6162  protected:
    6263    ServerConnection();
     
    6465
    6566  private:
    66 //     int getClientID(ENetPeer* peer);
    67 //     int getClientID(ENetAddress* address);
    68 //     ENetPeer* getClientPeer(int clientID);
    69 
    7067    ENetAddress* bindAddress_;
    71 
    7268    bool bListening_;
    7369
Note: See TracChangeset for help on using the changeset viewer.